如果没有响应,C插座将关闭连接

如果没有响应,C插座将关闭连接,c,sockets,timeout,C,Sockets,Timeout,我在等待客户回复时遇到了一个小问题。代码如下所示: 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秒,如果没有消息,执行另一件事

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

    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秒,如果没有消息,执行另一件事();功能?这不是连接问题(如客户端断开连接等)。这是我自己想要创建的限制。

您可以使用select()和timeout

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 */
}
可以将select()与timeout一起使用

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 */
}

您可以使用带有超时的
select
,等待套接字上的活动。或者使用
SO\RCVTIMEO
设置sockopt。您可以使用带有超时的
选择
来等待套接字上的活动。或者
setsockopt
使用
SO\u RCVTIMEO
。效果很好!非常感谢。工作很有魅力!非常感谢。