views:

156

answers:

3

I'm trying to write a chat server in C that allows communication between two clients using POSIX sockets. I'm not sure I have a good grasp on this concept or how I should set up the communication protocol between the clients and the server.

I know I need one socket to bind() the server port to so I can accept incoming connections from clients, but in order to have two clients connected at the same time do I need to create a socket for each of these clients when I accept() or should I accept() a client and then fork() so I can have another client accept? I'm not worried about concurrent chatting yet, it's more of a ping-pong approach where the clients need to wait for a recv() after they send() before they can type a new message.

+2  A: 

When you accept you get returned a new socket for that client, you can spawn a thread at that point to deal with that client. In that thread you can recv and send to that new returned socket to talk to your connected client.

You should continue to accept with the previous socket.

Your protocol that you define should dictate who sends messages in what order.

Brian R. Bondy
A: 

When you're using more than one socket at a time (i.e. in a three-way chat), the easiest way to handle the sockets is to block inside select() or poll(), which will return whenever data becomes available on at least one of the sockets. You can then use FD_ISSET() to figure out which socket(s) have data ready to read, and call recv() on them.

Jeremy Friesner
+3  A: 

You have two ways of handling multiple clients: using non-blocking IO, and using threads. For small things like chats I rather use non-blocking, as I don't have to worry about locks and threads. Check the select and poll functions.

The main loop would do something like this:

  1. build a set with all the fd's you want to listen
  2. wait for select to return
  3. use FD_ISSET to check for incoming connections on your main fd (the one you pass to listen). Then you can accept() and save the new fd in your connections list.
  4. handle the rest of the fd's you're interested in (loop through a list using FD_ISSET to check for active sockets).
Pablo Alejandro Costesich