How can I accept multiple clients to a TCP server?
Asked Answered
B

2

7

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
Boulevardier answered 15/12, 2014 at 21:12 Comment(0)
B
0

Turns out the pseudo code looks like:

while(1)     //before listen

pid = fork;  //right after accept

if(fork>0)
  close sd2 ( sd2 = accept(....) )
  continue
else
  run the rest of the program
Boulevardier answered 15/12, 2014 at 21:48 Comment(0)
R
3

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

Ranna answered 17/12, 2014 at 11:48 Comment(0)
B
0

Turns out the pseudo code looks like:

while(1)     //before listen

pid = fork;  //right after accept

if(fork>0)
  close sd2 ( sd2 = accept(....) )
  continue
else
  run the rest of the program
Boulevardier answered 15/12, 2014 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.