【发布时间】:2012-05-11 09:44:33
【问题描述】:
如何设置读写超时(套接字)?并测试它们?
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 秒后关闭连接。我该怎么做?
【问题讨论】:
-
read()不会关闭连接,您必须检查读取是否返回错误或0,然后使用close(fd)关闭连接。