【问题标题】:Handling time-out in C client-server program在 C 客户端-服务器程序中处理超时
【发布时间】:2011-07-10 22:12:34
【问题描述】:

我有一个小型客户端-服务器程序,我想在最大超时 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函数的代码。
  • 是这样的:code signal(SIGALRM, time_out);警报(10); cod = recv(conn, &buf, sizeof(buf), 0); boolean isNumber = validateNumber(buf); printf("收到的字符串:%s\n", buf);警报(0); // 停止计时器 if(!isNumber) { //服务器没有收到一个有效的整数 errorMsg = "请输入一个有效的整数!\n\0"; printf("发送错误信息..\n");发送(连接,错误消息,strlen(错误消息)+1,0); } 其他.. code

标签: c sockets timeout


【解决方案1】:

也许你可以使用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, ....);
}

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

【讨论】:

  • 我对我处理 time_out 的方式很满意,它工作正常,或者对我来说似乎是这样。这意味着服务器等待 10 秒来接收字符串;如果它接收到字符串,它会重置警报。问题在于我将消息发送到客户端的信号处理程序(time_out() 函数)。仅在客户端尝试将 smth 发送到服务器之后,该消息才出现,该连接已关闭。我很久没有在 C 领域工作了,如果我解释得不够清楚,很抱歉。
  • 我的错,我没有回答问题的核心。尽管如此,我(我们?)可能需要在您的客户端查看代码。也许您不刷新打印缓冲区?尝试在客户端的 init 中添加setbuf(stdout, NULL);
  • 这样总结:code printf("输入你想要的数字:\n"); fgets(输入,sizeof(输入),标准输入); if (input[strlen(input)-1] == '\n') { input[strlen(input)-1] = '\0'; //全行读取 cod = send(conn, input, strlen(input), 0); if (cod != strlen(input)) { fprintf(stderr, "向服务器发送数据时出错..\n");返回 1; } //服务器响应:cod = recv(conn, buf, sizeof(buf), 0); printf("服务器的响应是:\n\t %s \n", buf); code我在recv之前试过setbuf(stdout, NULL),但还是没有结果。
  • 我很确定它会因为 fgets() 无限期地等待输入,但我不知道如何处理这种特殊情况。我想要一些机制来强制客户端输出。
  • @joanna 几乎不可能阅读 cmets 中发布的代码,而是编辑您的问题并在此处发布/格式化代码。
猜你喜欢
  • 2020-06-09
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
相关资源
最近更新 更多