socketswebsocket

How can a server communicare with multiple clients : `client_fd`, `server_fd`?


I'm reading a PDF/book on socket programming by Breej.

I understand that a server listens on a specific port (say localhost:3000). When I connect to the server from Browser 1, it uses an ephemeral port like localhost:43215, and the server creates a client_fd for that connection (43215 <-> 3000).

Then, if I connect from Browser 2, another client_fd is created (e.g., 43216 <-> 3000).

My question is:

looks like a person working on a task & waiting for task simultaneously.


Solution

  • On Linux, the port listening activity on the server is just another form of socket descriptor monitoring.

    So it's possible to have a main server process that monitors a "set" of descriptors, one of which is the listening socket, and the rest are connected client sessions. As clients connect (and disconnect) you update the set dynamically (to add or remove the corresponding fd) and carry on monitoring.

    How you manage that set (e.g. using epoll(), poll(), select()) and whether you spawn new threads for the distinct handler activities is up to you, to get the balance of performance and responsiveness that you need in your application.