首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我使用javaudp去接收硬件设备的数据,但是在judp以后他就立马自动关闭了,请问怎么处理?

我使用javaudp去接收硬件设备的数据,但是在judp以后他就立马自动关闭了,请问怎么处理?

提问于 2018-09-26 09:51:00
回答 1关注 0查看 600

@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)

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档