如何使winsock2中的recv函数在特定时间后停止..? [英] How to make the recv function in winsock2 stop after a specific time..?

查看:108
本文介绍了如何使winsock2中的recv函数在特定时间后停止..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


在用于Windows桌面的Visual Studio 3013中用c ++开发Windows桌面控制台应用程序,它充当客户端并尝试连接到服务器。一旦与服务器的连接成功,它就会向
服务器发送握手信号并等待服务器的响应。我在这个应用程序中使用winsocks2。我正在使用的接收函数是一个阻塞调用

In an developing a Windows Desktop Console Application in c++ in Visual Studio 3013 for Windows Desktop, which acts as a client and tries to connect to a server. Once the Connection with the server is successful, it sends a handshaking signal to the server and waits for a response from the server. Iam using winsocks2 in this application. The receive function I am using is a blocking call

iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);



所以在我的服务器发送响应之前,客户端被阻止。我需要的是客户端只检查响应一段时间(例如10秒)。如果没有在这段时间内响应,我希望客户端与服务器断开连接。如何实现
这个?

So until my server sends a response, the client is blocked. What I need is the client to check for response only for a certain time (say 10 sec). If there is no response within this time frame ,I want the client to disconnect from the server. How to achieve this?

推荐答案

也许创建一个并行线程(例如使用 CreateThread ),等待10秒,然后执行
shutdown(ConnectSocket) closesocket(ConnectSocket)。这会导致
recv 异常终止。但如果 recv 正常返回,则中断线程并重新检查套接字可用性。(你可以使用事件等待10秒并中断或继续线程)。

Perhaps create a parallel thread (using CreateThread for example), which waits 10 s, then executes shutdown(ConnectSocket) and closesocket(ConnectSocket). This should cause recv to terminate abnormally. But if recv returns normally, then interrupt the thread and re-check the socket availability. (You can use an event to wait 10 s and either interrupt or continue the thread).


这篇关于如何使winsock2中的recv函数在特定时间后停止..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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