views:

88

answers:

3

Hello all , I have question. I create socket , connect , send bytes , all is ok.

and for receiving data i use recv function.

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.

Many Thanks.

+2  A: 

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.

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

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.

Daniel Earwicker
Thanks please one small example , select(...);after that recv ??
Armen Khachatryan
Oh, go on then.
Daniel Earwicker
Maybe I'm crazy, but I prefer `WSAEventSelect` and `WaitForSingleObject` over `select`. Just as I prefer `poll` on Unix. `select` is just old and weird looking. Every time I hear someone advocate it a part of me dies.
asveikau
Weird... what do you do with the dead parts?
Daniel Earwicker
Thank Youuuuuuuuuuuuuuuu , i accept you answer and more! :)
Armen Khachatryan
A: 

You have to call the select function prior to calling recv to know if there is something to be read.

Didier Trosset
A: 

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

Adil