【问题标题】:C sockets close connection if no response如果没有响应,C 套接字关闭连接
【发布时间】:2016-09-26 21:40:41
【问题描述】:

我在等待客户回复时遇到了一个小问题。代码如下所示:

    num_bytes_received = recv(recvFD, line, MAX_LINE_SIZE-1, 0);

    if(line[0] == 'R')
    {
        do_something();
    }

    if(line[0] == 'P')
    {
        do_another_thing();
    }

有什么简单的方法可以等待消息,比如说 30 秒,如果没有消息,执行 do_another_thing();功能?这不是连接问题的情况(例如客户端断开连接等)。这是我自己想要创造的限制。

【问题讨论】:

  • 您可以使用select 和超时来等待套接字上的活动。或setsockopt 使用SO_RCVTIMEO

标签: c sockets timeout


【解决方案1】:

您可以使用 select() 超时。

int ret;
fd_set set;
struct timeval timeout;
/* Initialize the file descriptor set. */
FD_ZERO(&set);
FD_SET(recvFD, &set);

/* Initialize the timeout data structure. */
timeout.tv_sec = 30;
timeout.tv_usec = 0;

/* select returns 0 if timeout, 1 if input available, -1 if error. */
ret = select(recvFD+1, &set, NULL, NULL, &timeout));
if (ret == 1) {
    num_bytes_received = recv(recvFD, line, MAX_LINE_SIZE-1, 0);
    if(line[0] == 'R')
    {
        do_something();
    }

    if(line[0] == 'P')
    {
        do_another_thing();
    }
} 
else if (ret == 0) {
    /* timeout */
    do_another_thing();
}
else {
    /* error handling */
}

【讨论】:

  • 像魅力一样工作!谢谢!
猜你喜欢
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
相关资源
最近更新 更多