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?
Thanks.
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.
You need to read up on ::listen()
and ::accept()
.
The former will set up your socket for listening. You then need a loop (probably in its own thread) which uses ::accept()
which will return each time a new connection arrives.
That loop should then spawn a new thread to which you should pass the file descriptor received from ::accept()
and then handles all I/O on that socket from thereon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With