简体   繁体   English

Java UDP DatagramSocket 停止接收

[英]Java UDP DatagramSocket stops receiving

I have a DatagramSocket where I'm receiving in a loop and it eventually just stops receiving packets.我有一个 DatagramSocket,我在其中循环接收数据,它最终只是停止接收数据包。 I send the server a hello message that establishes the connection.我向服务器发送一条建立连接的问候消息。 Then I start reciving packets as expected.然后我开始按预期接收数据包。 Eventually it just stops receiving.最终它只是停止接收。

The sending server has verified that they are still sending packets to the same address via tcp dump but eventually this code hangs on the receive call.发送服务器已验证他们仍在通过 tcp 转储将数据包发送到同一地址,但最终此代码挂在接收调用上。

Is there anything that would cause the socket to stop receiving?有没有什么会导致套接字停止接收?

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();

If you're behind NAT, the mapping will time out if there's no outbound traffic for too long. 如果您落后于NAT,如果没有出站流量的时间太长,映射将超时。 Make sure to send an outbound datagram every few minutes to keep the mapping active in the router. 确保每隔几分钟发送一次出站数据报,以使映射在路由器中保持活动状态。

Not clear from the question, whether you work with several DatagramSockets inside one process: This would be non-trivial.从问题中不清楚,您是否在一个进程中使用多个 DatagramSockets:这将是非常重要的。 See Java: Receiving an UDP datagram packet with multiple DatagramSocketsJava:Receiving an UDP datagram packet with multiple DatagramSockets

Unless using multicast, a newly created datagram socket will inherit the process' receiving cursor and clamp the existing one from receiving.除非使用多播,否则新创建的数据报套接字将继承进程的接收 cursor 并限制现有的接收。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM