【问题标题】:Read/print socket ouput while waiting on cin (w/o multithreading)在等待 cin 时读取/打印套接字输出(不支持多线程)
【发布时间】:2017-05-23 00:13:25
【问题描述】:

我有一个通过 TCP 套接字连接到服务器的客户端程序,如下所示:

int main ( )
{
    std::cout << "HunterChat client starting up" << std::endl;
    std::string cmd;
    std::string reply;
    bool cont = true;
    ClientSocket client_socket ( "localhost", PORT );
    try {   
        while(cont) {
                try {
                    std::cout << ">> ";
                    // std::getline(std::cin,cmd);
                    gets(cmd);
                    if(cmd.compare("logout") == 0) {
                        cont = false;
                        break;
                    }
                    client_socket << cmd;
                    client_socket >> reply;
                    std::cout << reply << std::endl;
                }
                catch ( SocketException& e) {
                    std::cout << "Exception was caught:" << e.description() << "\n";
                }
        }
    }
    catch ( SocketException& e ) {
        std::cout << "Exception was caught:" << e.description() << "\n";
    }

    return 0;
}

ClientSocket 是一个自定义类,可以让我设置和使用 TCP 连接;流操作符被重载,代码如下:

int status = ::send ( m_sock, s.c_str(), s.size(), MSG_NOSIGNAL );
if ( status == -1 )
{
    return false;
}
else
{
    return true;
}

TCP 连接本身工作正常,所以我不会在帖子中添加更多内容。问题是可用命令之一涉及将输入发送到客户端实例,而所述客户端仍在等待 cin 输入。这意味着只有当我在 cin 中输入内容时,服务器消息才会被读取和写入。我试图避免使用多线程,那么有没有办法让 cin 在没有它的情况下被中断?

【问题讨论】:

标签: c++ multithreading sockets tcp


【解决方案1】:

好吧,如果你真的想的话,你可以使用循环和函数kbhit() 来检查用户输入。但是,在我看来,线程是一个更好的解决方案。

#include <conio.h>
#include <iostream>

using namespace std;



int main()
{
    while(1)
    {
        if(kbhit())
        {
            char x = getch();
            // ...
        }
        // check messages asynchronously here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多