【问题标题】:Handler socket timers on read/write读/写处理程序套接字计时器
【发布时间】: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) 关闭连接。

标签: c++ sockets timeout


【解决方案1】:

尺寸明显不对:

setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
    sizeof(timeout) < 0);

删除&lt; 0。您可能从一些 if 中复制粘贴,然后将括号搞砸了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-25
    • 2016-01-28
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多