当网络连接不可用时阻止发送 UDP 数据
我有一个 C 应用程序,每隔几秒就向 UDP 服务器发送数据。如果客户端失去网络连接几分钟,然后恢复连接,它会将所有累积的数据发送到服务器,这可能会导致该客户端同时向服务器发出一百个或更多请求。
如果使用 UDP 传输过程中发生错误,是否有办法阻止这些消息从客户端发送?来自 UDP 客户端的 connect
调用是否有助于确定客户端是否可以连接到服务器?或者这只能通过 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);
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");
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您得到的行为是来自在套接字 sndbuf 中缓冲的数据报,如果无法立即发送这些数据报,您希望将其删除?
如果是这种情况,您可能会幸运地将 sndbuf 的大小设置为零。
警告——这个行为领域听起来非常接近“特定于实现”的领域。
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.
如此处所述,要检索 UDP 发送上的错误,您应该使用
connect
之前,然后是send
方法,但在 Linux 上,无论有没有connect
似乎都有相同的行为。As explained here, to retrieve errors on UDP send you should use a
connect
before, then thesend
method, yet on Linux it seems to have the same behaviour with or withoutconnect
.