I want to write my own little chat server in C on a MacOS machine. Now I want to connect to all clients, that are online and let the connection open, to be able to receive and send messages. The problem is that I only know, how to have one socket connection at a time open. So only one client can connect so far and chatting like that is kinda boring ;)
views:
311answers:
7One option is to use multithreading with the pthreads library. Another option is to use asynchronous I/O with the select(2)
call. With select(2)
, you open a bunch of sockets, and then you can poll each one to see if it has data. If it has data, you read it, otherwise you move on to the next socket.
Basically you need to have a listening socket on your chosen port. Once a connection is established to the listening socket, you need to open a new socket on a different port number and hand the client over to this new socket. It will be best to try and use a pre-written socket library as rolling your own here is going to be a complex process.
Try searching http://sourceforge.net for some sample libraries.
take a look at select, pselect and poll.
I've never use them my self, but I suspect they are for what you want to do.
There is no problem to have multiple connected socket in one program, and you don't need to mess with multithreading. Just keep opening connections as you used to. If all your clients connects to the same listener, just do not close the listener after accept()
- it will keep listening for more incoming connections.
Use select()
or poll()
to check for incoming data on all opened sockets. Do not forget to included listening socket into listed of descriptors for select()
- incoming connection is an event select()
detects.
It is really very simple. No rocket science.
The simplest solution for a small chat server is probably to use select() or pselect().
Have a look at the excellent Beej's Guide to Network Programming. In his select() tutorial, he builds a small chat server.