简体   繁体   English

当网络连接不可用时,防止发送UDP数据

[英]Prevent UDP data from being sent when network connection is unavailable

I have a C application that sends data to a UDP server every few seconds. 我有一个C应用程序,每隔几秒就会将数据发送到UDP服务器。 If the client loses it's network connection for a few minutes and then gets it's connection back, it will send all of the accumulated data to the server which may result in a hundred or more requests coming into the server at the same time from that client. 如果客户端丢失了几分钟的网络连接然后恢复连接,它将把所有累积的数据发送到服务器,这可能导致一百个或更多请求同时从该客户端进入服务器。

Is there any way to prevent these messages from being sent from the client if an error occurs during transmission using UDP? 如果在使用UDP传输期间发生错误,有没有办法阻止从客户端发送这些消息? Would a connect call from the UDP client help to determine if the client can connect to the server? 来自UDP客户端的connect呼叫是否有助于确定客户端是否可以连接到服务器? Or would this only be possible using TCP? 或者这只能使用TCP吗?

int socketDescriptor; 
struct sockaddr_in serverAddress;

if ((socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
    printf("Could not create socket. \n");
    return;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(server_ip);
serverAddress.sin_port = htons(server_port);

if (sendto(socketDescriptor, data, strlen(data), 0, 
                  (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
{  
   printf("Could not send data to the server. \n");
   return;
}

close(socketDescriptor);

It sounds like the behavior you're getting is from datagrams being buffered in socket sndbuf, and you would prefer that those datagrams be dropped if they can't immediately be sent? 听起来你得到的行为来自在socket sndbuf中缓冲的数据报,如果无法立即发送这些数据报,你会希望删除这些数据报吗?

If that's the case, you might have luck setting the size of the sndbuf to zero. 如果是这种情况,您可能很幸运将sndbuf的大小设置为零。

Word of warning--this area of behavior sounds like it treads very close to "implementation specific" territory. 警告的话 - 这个行为区域听起来非常接近“特定于实施”的领域。

正如这里所解释的,要在UDP上发送错误,你应该使用之前的connect ,然后使用send方法,但在Linux上它似乎具有相同的行为,有或没有connect

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

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