内容:简单的UDP通讯例子。
Receiver:
public class Receiver {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
//UDP接收端
ds = new DatagramSocket(8080);
//定义将UDP的数据包接收到什么地方
byte[] buf = new byte[1024];
//定义UDP的数据接收包
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while (true) {
//接收数据包
ds.receive(dp);
String string = new String(dp.getData(), 0, dp.getLength());
System.out.println("length:" + dp.getLength() + "->" + string);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}
}
}
Sender:
public class Sender {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
//定义一个UDP的Socket来发送数据
ds = new DatagramSocket();
String hello = "hello world";
//定义一个UDP的数据发送包来发送数据,inetSocketAddress表示要接收的地址
DatagramPacket dp = new DatagramPacket(hello.getBytes(),
hello.getBytes().length, new InetSocketAddress("127.0.0.1", 8080));
for (int i = 0; i < 10; i++) {
ds.send(dp);
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null) ds.close();
}
}
}