62,633
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(null); // 指定Null很重要,否则Java会自动随机选个可用端口来绑定
ds.setReuseAddress(true); // 绑定之前先设置Reuse
ds.bind(new InetSocketAddress(9999)); // 然后再绑定
System.out.println("REUSEADDR is enabled: " + ds.getReuseAddress()); // 返回结果是true,说明才有效
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
ds.receive(dp);
System.out.println("RECEIVE: " + new String(dp.getData()));
}
public static void main(String[] args) throws Exception {
String msg = "Hello world!";
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.length(), new InetSocketAddress("255.255.255.255", 9999));
ds.send(dp);
System.out.println("SEND: " + new String(dp.getData()));
}