具有多个连接的C ++ Server套接字

时间:2014-11-19 01:14:10

标签: c++ multithreading sockets

我正在尝试创建程序,它托管服务器并允许多个客户端加入服务器。我能够创建服务器套接字,它只允许一个连接,但我无法使我的多线程知识适应它。我每当客户端连接时(创建新线程时)代码都会抛出运行时错误。我的代码是:         结果;         int recvbuf;         int dataReceived;

int save(int key_stroke,char *file);


class ClientHandler{
public:
    void operator()(SOCKET s){
        try{
            do{
            result = recv(s,(char*)&recvbuf,4,0);
            dataReceived = ntohl(recvbuf);
            if(result>0){
                save(dataReceived,"log.txt");
            }else{
                cout << "CONNECTION LOST!" << endl;
            }

            }while(result > 0);
        }catch(...){}
    }

};


int main()
{
    WSAData wsa;
    WORD version = MAKEWORD(2,1);

    WSAStartup(version, &wsa);

    SOCKET Listener = socket(AF_INET,SOCK_STREAM,NULL);
    SOCKET Connect = socket(AF_INET,SOCK_STREAM,NULL);

    SOCKADDR_IN Server;

    Server.sin_addr.s_addr = INADDR_ANY;
    Server.sin_family = AF_INET;
    Server.sin_port = htons(5125);

    int sizeOf = sizeof(Server);
    bind(Listener, (SOCKADDR*)&Server , sizeOf);
    listen(Listener,100);
    cout << "Listening" << endl;
    for(;;){
            Connect = accept(Listener,(SOCKADDR*)&Server , &sizeOf);
            cout << "CONNECTION MADE!" << endl;
            thread t1((ClientHandler()) ,Connect);
          }

}

2 个答案:

答案 0 :(得分:3)

这是因为您在创建线程后立即删除了该线程。你需要将它们保存在某个地方:

std::vector<std::unique_ptr<std::thread>> threads;
for (;;) {
    // as before
    threads.emplace_back(new std::thread((ClientHandler()), Connect));
}

答案 1 :(得分:0)

由于您正在使用C ++套接字编程,您可能希望使用QT C ++库。它是免费的,开源的,并且已经解决了大多数问题,并且是一个很好的,记录良好的api:

http://qt-project.org/doc/qt-5/qtnetwork-threadedfortuneserver-example.html

所有例子: http://qt-project.org/doc/qt-5/examples-network.html