Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Thanks.

like image 714
Lefsler Avatar asked May 23 '12 15:05

Lefsler


2 Answers

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.

like image 116
fduff Avatar answered Oct 21 '22 20:10

fduff


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.

like image 41
Alnitak Avatar answered Oct 21 '22 22:10

Alnitak