windows C++ 套接字窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2287269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ socket windows
提问by Armen Khachatryan
I have question. I create socket , connect , send bytes , all is ok.
我有问题。我创建套接字,连接,发送字节,一切正常。
and for receiving data i use recv function.
对于接收数据,我使用 recv 函数。
char * TOReceive= new char[200];
recv(ConnectSocket, TOReceive , 200, 0);
when there are some data it reads and retuns, succefull , and when no data waits for data, all i need to limit waiting time, for example if 10 seconds no data it should return.
当有一些数据读取并返回时,成功,当没有数据等待数据时,我只需要限制等待时间,例如如果 10 秒没有数据它应该返回。
Many Thanks.
非常感谢。
回答by Daniel Earwicker
Windows sockets has the select
function. You pass it the socket handle and a socket to check for readability, and a timeout, and it returns telling whether the socket became readable or whether the timeout was reached.
Windows 套接字具有该select
功能。您将套接字句柄和套接字传递给它以检查可读性和超时,然后它返回告诉套接字是否变得可读或是否已达到超时。
See: http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx
请参阅:http: //msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx
Here's how to do it:
这是如何做到的:
bool readyToReceive(int sock, int interval = 1)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
timeval tv;
tv.tv_sec = interval;
tv.tv_usec = 0;
return (select(sock + 1, &fds, 0, 0, &tv) == 1);
}
If it returns true, your next call to recv
should return immediately with some data.
如果它返回 true,则您的下一次调用recv
应立即返回一些数据。
You could make this more robust by checking select
for error return values and throwing exceptions in those cases. Here I just return true
if it says one handle is ready to read, but that means I return false
under all other circumstances, including the socket being already closed.
您可以通过检查select
错误返回值并在这些情况下抛出异常来使其更加健壮。在这里,true
如果它说一个句柄已准备好读取,我就返回,但这意味着我false
在所有其他情况下都返回,包括套接字已经关闭。
回答by Didier Trosset
You have to call the select
function prior to calling recv
to know if there is something to be read.
您必须在调用select
之前调用该函数recv
才能知道是否有要读取的内容。
回答by Adil
You can use SO_RCVTIMEO socket option to specify the timeout value for recv() call.
您可以使用 SO_RCVTIMEO 套接字选项来指定 recv() 调用的超时值。