【问题标题】:C++ Server/Client Chat ProgramC++ 服务器/客户端聊天程序
【发布时间】:2018-04-30 07:11:58
【问题描述】:

我正在开发一个服务器-多客户端聊天程序,并制作了一种方法,可以将服务器键入的输入打印到其所有各自的客户端。

方法:

void *admin_handler (void *ptr) {
    char strBuf [100000];
    const char strExit [20] = "Server: terminated.";

    while(1) {
        scanf ("%s", strBuf);
        int i;
        for (i=0; i < nClient; i++){
            if (strcmp(strBuf,"Exit") == 0){
                write (nFDList [i], strExit, strlen (strExit) + 1);
                quick_exit (EXIT_SUCCESS);
            }
            else {
                write (nFDList [i], strBuf, strlen (strBuf) + 1);
            }
        }
    };
}

但是,当我在服务器端输入“退出”时,它只打印“服务器:终止”。到我打开的第一个客户端,当我输入任何其他内容时,它会将消息从服​​务器打印到所有客户端。如何让服务器将 strExit 打印到 strBuf 等所有客户端?

注意:nFDList[i] 是一个存储客户端的数组。

【问题讨论】:

  • 一些rubber duck debugging 应该解决它。我的主要建议是将输入处理功能、“命令”解析功能和发送至所有功能分离为单独的功能。应该可以更简单地避免此类问题。
  • 我只是不明白 if 语句的 write 与 else 语句 write 的工作方式不同...唯一的区别是 strBuf 和 strExit。
  • 对第一个客户来说效果很好。然后你退出。您的程序在退出后如何继续写入所有其他客户端?
  • 这就是 else 语句中 write 的作用......它将服务器输入写入所有客户端
  • 一般情况下是learn how to debug your programs。尤其是学习如何使用调试器逐行执行代码。然后就会很清楚问题是什么。

标签: c++ sockets network-programming


【解决方案1】:

让它打印“服务器:终止。”对于所有客户,我必须修改我的代码如下:

void *admin_handler (void *ptr) {
    char strBuf [100000];
    const char strExit [20] = "Server: terminated.";
    while(1) {
        scanf ("%s", strBuf);
        int i;
        for (i=0; i < nClient; i++){
            if (strcmp(strBuf,"Exit") == 0){
                for (i=0; i < nClient; i++){
                    write (nFDList [i], strExit, strlen (strExit) + 1);
                }
                quick_exit (EXIT_SUCCESS);
            }
            else {
                write (nFDList [i], strBuf, strlen (strBuf) + 1);
            }
        }
    };
}

【讨论】:

    【解决方案2】:

    因为,正如您正确指出的那样,发送正常消息和关闭消息之间的唯一区别是发送中使用的文本,那么您可以通过只发生一次发送来“使真实成为真实”逻辑和操作输入。

    这是一个更干燥的建议替代方案:

    void *admin_handler (void *ptr) {
        char strBuf [100000];
        char flagExit = 0;
        const char strExit [20] = "Server: terminated.";
        while(1) {
            scanf ("%s", strBuf);
    
            if (strcmp(strBuf, "Exit") == 0){
                strncpy(strBuf, strExit, strlen(strExit));
                flagExit = 1;
            }
    
            int i;
            for (i=0; i < nClient; i++){
                write (nFDList [i], strBuf, strlen (strBuf) + 1);
            }
    
            if (flagExit) {
                quick_exit (EXIT_SUCCESS);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-17
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多