62,629
社区成员
发帖
与我相关
我的任务
分享

[/quote]
我在我的代码 ds.send(dp) 和 ds.close() 之间加了一句 Thread.sleep(1000) 就可以收到了。不加这一句的话就收不到。接收端是一直开着的。 难道不加这一句send和close就是同时执行的吗? 好奇怪的现象。。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UdpSender {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(8888);
Scanner scanner = new Scanner(System.in);
System.out.println("输入要发送的信息:");
while(true){
String msg = scanner.nextLine();
byte[] buf = msg.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("localhost"), 10000);
ds.send(dp);
System.out.printf("%s sent!", msg);
if("quit".equalsIgnoreCase(msg))
break;
}
ds.close();
}
}
接收端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiver {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
String data = null;
while(!"quit".equalsIgnoreCase(data)){
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
data = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip+"::"+data);
}
System.out.println("byebye");
ds.close();
}
}