Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I accept multiple clients to a TCP server?

I currently have a TCP server set up that can accept a connection from a client and echo whatever the client inputs. How would I go about making multiple clients connect to the server and have their input sent to all clients?

It appears I should fork, but I'm not fully sure how...

On the server, should I place an infinite loop starting from accept (or listen?) that will fork when there is a new connection? Then on the child process I would have to close the socket from a previous process and connect to the new one, but once again I'm not fully sure.

What would the pseudo code look like in regards to just the forks and socket manipulation? My guess:

while(1) //before connection or accept?

pid = fork()

if(pid==0)
  // open socket from client
  // run the rest of the code 
  // end process when client disconnects
else
  // close socket from client
like image 654
countofmontecristo Avatar asked Dec 15 '14 21:12

countofmontecristo


1 Answers

You may find in the Internet many examples, first I have found: http://www.tutorialspoint.com/unix_sockets/socket_server_example.htm

Keep in mind that process (or thread) per client approach does not scale well. Modern servers use non-blocking main dispatching loop. Take a look at libevent.

Here is example of echo server using libevent: https://github.com/jasonish/libevent-examples/tree/master/echo-server

like image 117
Alexander Altshuler Avatar answered Sep 28 '22 01:09

Alexander Altshuler