不说UDP是什么了,没意思,直接上demo
测试demo时放在不同得类里面,先启动接收类,再启动发送类。
发送端代码
public static void main(String[] args){
DatagramSocket ds=null;
DatagramPacket dpSend=null;
int port=1515;//发送消息到此端口
try
{
ds=new DatagramSocket();
for(int i=0;i<5;i++)
{
byte[] data=("UDP 客户端"+i).getBytes();
dpSend=new DatagramPacket(data,data.length,InetAddress.getByName("127.0.0.1"),port);
ds.send(dpSend);
Thread.sleep(1000);
}
ds.close();
}
catch(IOException | InterruptedException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
接收端代码
public static void main(String[] args) throws SocketException {
int port=1515;//接收此端口消息
DatagramSocket socket= new DatagramSocket(port);
System.out.println("UDP服务器已启动.....");
byte[] buffer = new byte[8192];
while (true) {
if(socket.isClosed()){
System.out.println("UDP已关闭");
}
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.length);
try {
socket.receive(incoming);
String msg = new String(incoming.getData(),0,incoming.getLength());
System.out.println("发送端发送的内容是:" + msg);
System.out.println("发送端IP:" + incoming.getAddress());
System.out.println("发送端端口:" + incoming.getPort());
} catch (Exception e) {
e.printStackTrace();
}
}
}
发送端发送消息到远程服务器得某个端口下, 远程服务器的接收端接收此端口下得消息并解析。