Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Server socket with multiple connections

I am trying to create program,which hosts a server and lets multiple clients to join a server.I am able to create server socket,which allows only one connection,but I am unable to adapt my multithreading knowledge to it.My code throws runtime error whenever client connects(when creating new thread).There is my code: int result; 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);
          }

}
like image 562
ESipalis Avatar asked Jun 07 '26 01:06

ESipalis


1 Answers

That's because you're deleting your thread as soon as you create it. You need to save them somewhere:

std::vector<std::unique_ptr<std::thread>> threads;
for (;;) {
    // as before
    threads.emplace_back(new std::thread((ClientHandler()), Connect));
}
like image 85
Barry Avatar answered Jun 08 '26 20:06

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!