I implemented a multi client chat server in C using socket programming. In a multi client chat server, N clients are connected to a server and send messages. In this program, one of the clients send messages to the server and it will send back the messages to all other clients. I implemented it using TCP.
A simple Client-Server Interaction
In the server program, first is the establishment of connection to a port. we get the socket file descriptor ,
int socket(int domain, int type, int protocol);
‘setsockopt’ is used for losing the pesky “Address already in use” error message. Once we have a socket, we might have to associate that socket with a port on our local machine. This can be done by using the ‘bind’.
int bind(int sockfd, struct sockaddr *my_addr, int addrlen);
We want to wait for incoming connections, we use ‘listen’ in this situation.
int listen(int sockfd, int backlog);
sockfd is the usual socket file descriptor from the socket() system call. backlog is the number of connections allowed on the incoming queue .
In the case of a server, it wants to listen for incoming connections as well as keep reading from the connections it already have. select() gives the power to monitor several sockets at the same time. It’ll tell you which ones are ready for reading, which are ready for writing, and which sockets have raised exceptions.
int select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
If we want to see if we can read from standard input and some socket descriptor, sockfd, just add the file descriptors 0 and sockfd to the set readfds. The parameter numfds should be set to the values of the highest file descriptor plus one. When select() returns, readfds will be modified to reflect which of the file descriptors we
selected which is ready for reading. After ‘select’, it run through the existing connections looking for data to read. If we got one, new connections are handled and the new file descriptor is added to the master set by keeping track of the maximum file descriptor. If there is no need to handle new connection, handle data from a client. If there is any data in the recv_buf, it can be received by using recv().Or , the data is send to all other clients by using the function send().
In the client program, first is the establishment of connection to the server and running on the localhost. Connection is established by using connect(). Then select() is used for either reading or writing as in the server program. It sends message to the server from the keyboard input using stdin. If there is data in the recv_buf, it receives data using recv().
The code of this program is available in https://bitbucket.org/vidyakv/network-programming/changeset/7f19f9145ab9