处理C客户端 - 服务器程序中的超时

时间:2011-03-08 07:44:31

标签: c sockets timeout

我有一个小型客户端 - 服务器程序,我希望在最长超时10秒后关闭与客户端的连接。我有一个警报,关闭连接的功能和警报处理程序如下所示:

void closeClient() {
    int nr = close(conn);
    if (nr == 0)
       printf("Client connection closed.\n");
    else {
      printf("Error while closing client connection. Error code: %d\n",errno);
      exit(1);
    }
    exit(0); // Process ends after serving the client
}

void time_out(int signal) {  
    printf("Time out.\n");

    char* msg = "Time out.Connection to server is closed\n\0";
    send(conn, msg, strlen(msg),0);
    closeClient(conn);  
    exit(1);
}

问题是客户端只有在尝试向服务器发送内容时才会打印消息(“Time-out.Connection to the server closed”)(在连接已经关闭之后)。我无法弄清楚为什么。一些建议?

1 个答案:

答案 0 :(得分:0)

也许你可以使用select()并在最后一个参数中给它一个超时值?

一些事情:

fd_set readset;
struct timeval timeout = {10, 0}; // 10 sec. timeout
FD_ZERO( &readset)
FD_SET( conn, &readset);
int status = select( conn+1, &readset, NULL, NULL, &timeout);
if(status == 0) // timeout reached
{
   // close conn
}
else if(status == -1)
{
   // handle error
}
else
{
   // data ready to be received
   status = read(conn, ....);
}

请务必每次检查您的返回值。