demonofnight demonofnight - 2 months ago 17
C++ Question

Multiple connections on the same port socket C++

I need to accept multiple connections to the same port.
I'm using socket in C++, i want to do something like the SSH do.
I can do an ssh user@machine "ls -lathrR /" and run another command to the same machine, even if the first one still running.

How can i do that?



What you want is a multithreaded socket server.

For this, you need a main thread that opens up a socket to listen to (and waits for incoming client connections). This has to go into a while loop of some sort.

Then, when a client connects to it, the accept() function will unblock and at that point you need to serve the client request by passing on the request to a thread that will deal with it.

The server side will loop back and wait for another connection whilst the previous thread carries on its task.

You can either create threads as you need, or use a thread pool which might be more efficient (saving on time initialising new threads).

Have a look here for some more details. Look for multithreaded server socket on the web, specifically bind(), listen() and accept() from the server side.