您如何设置读写超时(套接字)?并测试它们?
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
}
因此,如果我使用 telnet 进行测试,然后输入“hello”,控制台“挂起”,因为读取被阻塞。但是,当它挂起超过 3 秒时,超时什么也不做。我希望读取在挂起 3 秒后关闭连接。我该怎么做呢?