Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client Server multiple connections in C

I am trying to reason about how a simple server implemented in C with sockets can handle concurrent clients. Let's say a simple server waits for a client to connect and then read a message sent from the client. read() is a blocking function so the server will block until a client writes to it. If we assume two clients are concurrently writing to the server. The server will wake up to one of them but what will happen to the other one? is the server still "listening" while handling the request from the first client? I know that the bind function takes an int as the second argument that specifies the backlog (5 by default). does that mean that only 5 clients can connect concurrently to a server? If thats true, how are servers that handle multiple concurrent connections are implemented?

like image 438
Keeto Avatar asked Mar 15 '23 09:03

Keeto


2 Answers

The select(2) and poll(2) system calls were invented to deal with this exact situation (with non-blocking sockets).

Then there is a multi-process approach with fork(2), and then, of course, the server could be implemented with threads.

The best solution for your case depends on your specific requirements.

like image 52
Nikolai Fetissov Avatar answered Mar 18 '23 00:03

Nikolai Fetissov


You should threads. Usually servers have a main thread which listens for connection. If a connection is made the main thread created another thread and passes that connection to the newly created thread. This way the connections are responded while main thread is still able to listen for new connections.

Edit: Here is the listen():

listen(int socket_fd, int backlog)

For a given listening socket kernal maintains two queue.

  • An incomplete connection queue for which SYN has been come but three-way handshaking (TCP) is not done completely. (SYN_RCV state) A complete connection queue
  • Three-way handshaking done. (ESTABLISHED state) backlog argument historically specify sum of both queues. But there is no formal definition of what backlog means.
like image 31
Ehsan Ab Avatar answered Mar 17 '23 22:03

Ehsan Ab