@PostConstruct
public String recv() throws Exception {
DatagramSocket ds = new DatagramSocket(20055);
new Thread(() -> {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try {
System.out.println("准备接收..");
// ds.setSoTimeout(2000);
ds.receive(dp);
} catch (IOException e) {
System.out.println("接收失败..");
e.printStackTrace();
}
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String de = new String(dp.getData(), 0, dp.getLength());
if (de.equals("exit")) {
System.out.println(ip + "退出会话.....");
break;
}
System.out.println(ip + ":" + port + "===>" + de);
Gson gson = new Gson();
String jsonStr = gson.toJson(de);
//每次得到数据存数据库或缓存
System.out.println("接收数据;" + jsonStr);
}
}).start();
//关闭资源
ds.close();
return null;
}
public void action() {
System.out.println("bean has been init.");
}
}
错误信息:
准备接收..
接收失败..
java.net.SocketException: Socket closed
at java.net.DualStackPlainDatagramSocketImpl.checkAndReturnNativeFD(DualStackPlainDatagramSocketImpl.java:260)
at java.net.DualStackPlainDatagramSocketImpl.receive0(DualStackPlainDatagramSocketImpl.java:117)
at java.net.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)
at java.net.DatagramSocket.receive(DatagramSocket.java:812)
at com.zukai.connectionudp.UdpReceive.lambda$0(UdpReceive.java:71)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-1" java.lang.NullPointerException
at com.zukai.connectionudp.UdpReceive.lambda$0(UdpReceive.java:76)
at java.lang.Thread.run(Thread.java:748)
相似问题