Java UDP DatagramSocket停止接收

时间:2015-12-16 21:31:35

标签: java sockets udp

我有一个DatagramSocket,我在循环中接收它,它最终只是停止接收数据包。我向服务器发送一条建立连接的hello消息。然后我按预期开始收集数据包。最终它会停止接收。

发送服务器已经验证他们仍在通过tcp转储将数据包发送到同一地址,但最终此代码会在接收呼叫中挂起。

是否有任何会导致套接字停止接收的内容?

String hello = "hello";
InetAddress IPAddress = InetAddress.getByName("serveraddress");

DatagramPacket outboundPacket = new DatagramPacket(hello.getBytes(),hello.getBytes().length, IPAddress, 54321 );
DatagramSocket registerSocket = new DatagramSocket(61646);
registerSocket.send(outboundPacket);
int count = 0;
while(!done){

    count++;
    byte[] inboundData = new byte[1368];
    DatagramPacket inboundPacket = new DatagramPacket(inboundData,inboundData.length);

    System.out.println(registerSocket.getPort());
    System.out.println(registerSocket.getLocalPort());

//Eventually locks up here after hundreds of successful receives
    registerSocket.receive(inboundPacket);

    byte[] data = inboundPacket.getData();
    String test = new String(data, "ISO-8859-1");
    System.out.println(test+"---"+count);
}

registerSocket.close();

1 个答案:

答案 0 :(得分:2)

如果您在NAT后面,如果没有出站流量太久,映射将会超时。确保每隔几分钟发送一个出站数据报,以使映射在路由器中保持活动状态。