C ++ Socket Windows

I have a question. I create a socket, connect, send bytes, everything is in order.

and to receive data, I use the recv function.

char * TOReceive= new char[200]; recv(ConnectSocket, TOReceive , 200, 0); 

when there is some data that it reads and reconfigures is sucefull, and when no data is waiting for data, I need to limit the wait time, for example, if there is no data for 10 seconds that it should return.

Many thanks.

+4
source share
3 answers

Windows sockets have a select function. You give it a socket descriptor and socket to check for readability and a timeout, and it returns a message indicating whether the socket has become readable or a timeout has been reached.

See: 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 recv call should immediately return to some data.

You can make this more reliable by checking select for the returned error values ​​and throwing exceptions in these cases. Here, I simply return true if it says that one descriptor is ready to read, but that means that I return false under all other circumstances, including an already closed socket.

+6
source

You must call the select function before calling recv to find out if there is something to read.

0
source

You can use the SO_RCVTIMEO socket option to specify the timeout value for calling recv ().

0
source

Source: https://habr.com/ru/post/1301670/


All Articles