在等待cin时读取/打印套接字输出(无多线程)

时间:2017-05-23 00:13:25

标签: c++ multithreading sockets tcp

我有一个客户端程序通过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连接; stream运算符重载了以下代码:

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

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

1 个答案:

答案 0 :(得分:0)

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

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

using namespace std;



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