使recv_from函数无阻塞 [英] Making recv_from function non-blocking

查看:139
本文介绍了使recv_from函数无阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究udp服务器/客户端应用程序。为了查明是否有任何客户端关闭,服务器向客户端发送握手消息。然后,服务器等待客户端的响应以发送一些数据以确保客户端处于活动状态。为此,服务器阻止调用recv_from(),除非客户端回复,但如果客户端关闭,服务器将无限制地阻止调用recv_from。我想在我的服务器上实现这样的功能,以便它在调用recv_from等待特定时间(比如2秒)。如果在2秒内没有从客户端收到数据,则认为客户端已死,并且recv_from返回。有什么办法吗?我搜索了互联网,但找到了设置MSG_DONTWAIT标志的解决方案,当没有收到数据时立即返回,但在我的情况下,我不希望recv_from立即返回但等待特定持续时间的数据,并且当没有收到数据时那个特定的持续时间,recv_from函数应该重新调整。感谢任何帮助。

I am working on udp server/client application. For finding out if any of the client is down, server sends a handshake message to the client. Then, the server waits for the response of client to send some data to assure that the client is active. For this the server blocks in call to recv_from() unless the client replies back, but if the client is down, the server blocks infinitely in call to recv_from. I want to implement such a functionality on my server so that it waits in call to recv_from for a specific time (say 2 secs). If no data received from the client within 2 seconds, the client is considered to be dead and recv_from returns. Is there any way to do it? I searched internet but found solutions like setting MSG_DONTWAIT flag that returns immediately when no data received, but in my case, I don''t want recv_from to return immediately but wait for data for a specific duration of time, and when no data received for that specific duration, the recv_from function should retun. Any help is appreciated.

推荐答案

这是错误的方法,你应该使用非阻塞套接字(参见 http://msdn.microsoft.com/en-us/library/windows/desktop/ms740121( v = vs.85).aspx [ ^ ])。为每个客户端保留一个状态表,并在收到消息时标记表中的时间。定期检查状态表,如果在超过超时时间内没有收到任何消息,请将客户端标记为无响应。
This is the wrong way to do it, you should use a non-blocking socket (see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740121(v=vs.85).aspx[^]). Keep a state table for each client and whenever a message is received mark the time in the table. Check your state tables periodically and if no message has been received in less than the timeout time, mark the client as not responding.


这篇关于使recv_from函数无阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆