【问题标题】:Client-Server C++ alternative for _kbhit() function_kbhit() 函数的客户端-服务器 C++ 替代方案
【发布时间】:2018-07-09 12:56:44
【问题描述】:

我的项目是一个客户端-服务器应用程序 (C++),更具体地说是一个群聊。

我在 VS17 中以 2 个不同的解决方案构建了客户端和服务器。

现在,我的问题是,当我想将消息从一个客户端发送到服务器 - 并将消息重定向到连接的其他客户端时 - 我不想成为阻塞函数,所以我 used _kbhit() 函数,但我不能正常工作。除了kbhit() + getch()cin 之外,还有什么替代方法可以在客户端输入?

客户

char buffer[20];
int point = 0;

while (1)
{       
        if (!_kbhit()) {

            char cur = _getch();
            if (point > 19) 
                point = 19;
            std::cout << cur;
            if (cur != 13)
                buffer[point++] = cur;
            else {
                buffer[point] = '\0';
                point = 0;
            }

        }
        BytesReceived = recv(sock, buf, 4096, 0);
        if (BytesReceived != 0 && BytesReceived != -1)
        {
            cout << BytesReceived << endl;
            cout << string(buf, 0, BytesReceived) << endl;
            ZeroMemory(buf, 4096);
        }

    //cin >> userInput;
    // non blocking input 

    //if(userInput.size()>0)
        //int sendResult = send(sock, userInput.c_str(), userInput.size(), 0);
        int sendResult = send(sock, buffer, point+1, 0);

【问题讨论】:

    标签: c++ input client-server nonblocking


    【解决方案1】:

    在 ncurses 中,您可以尝试 nodelay() 函数将 getch() 转换为非阻塞调用,如果没有可用的按键,则返回 ERR。

    【讨论】:

      【解决方案2】:

      我认为应该是:

      if (_kbhit () != 0) {
          ....
      

      见:https://msdn.microsoft.com/en-us/library/58w7c94c.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-18
        • 2023-02-20
        • 2021-12-24
        • 1970-01-01
        • 2014-04-15
        • 1970-01-01
        • 2017-01-08
        相关资源
        最近更新 更多