How do you set timeouts with read and write (sockets)? and test them?
struct timeval timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
sizeof(timeout));
setsockopt (fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
sizeof(timeout));
string temp;
while (1) {
char buf [20];
ssize_t e = read(fd, buf, 20);
// convert current buf into string
// add current string to temp
// check if end of temp == \r\n\r\n
// if yes break
}
So if I use telnet to test this, and type in ‘hello’, the console “hangs” because the read is blocking. However when it hangs past 3 seconds, the timeout does nothing. I want the read to close the connection after hanging for 3 seconds. How do I do this?
The size is obviously wrong:
Drop the
< 0. You probably copy pasted from some if and then botched the parentheses.