开发者

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. 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? Would a connect call from the UDP client help to determine if the client can connect to the server? Or would this only be possible using TCP?

int socketDescriptor; 
struct sockaddr_in serverAddress;

if ((socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
    printf("Could not create socket. \n");
    开发者_JAVA技巧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?

If that's the case, you might have luck setting the size of the sndbuf to zero.

Word of warning--this area of behavior sounds like it treads very close to "implementation specific" territory.


As explained here, to retrieve errors on UDP send you should use a connect before, then the send method, yet on Linux it seems to have the same behaviour with or without connect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜