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.
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
selectandpollfunctions.The main loop would do something like this:
selectto returnFD_ISSETto check for incoming connections on your main fd (the one you pass to listen). Then you canaccept()and save the new fd in your connections list.FD_ISSETto check for active sockets).