- import java.io.*;
- import java.net.*;
- public class UdpReceiveDemo
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket ds = new DatagramSocket(10001);
-
- while(true)
- {
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
-
- ds.receive(dp);
-
- byte[] data = dp.getData();
- String str = new String(data,0,dp.getLength());
- String ip = dp.getAddress().getHostAddress();
- System.out.println(str + ip);
- }
- ds.close();
-
- }
- }
复制代码 上述代码,如果注释掉最后一行ds.close()就可以成功运行
但是如果不注释掉的话就会出错,程序无法运行
请大家给解释下,谢谢
|