
Sockets: A Multi-Client Chat Server
A chat server and client talk over TCP sockets. The server accepts up to ten connections, gives each client its own thread, relays every message to everyone else in the room, and saves the conversation to a file.
10
connections accepted at once
1
thread per client
2
locks on shared state
30 s
between automatic backups
Problem
Understanding the challenge and user needs
A server that waits on one client cannot hear another. Serving several people at once means several threads, and those threads then share a list of who is connected and a history of what has been said.
Approach
Strategy and methods used to address the problem
The server's main loop only accepts connections and starts a thread for each. A client's first message is its name, and the server tells the newcomer who is already in the room. One lock guards the client list and a second guards the history, so a message can reach every other client while someone else joins or leaves.
What the server keeps, and what guards it
| Shared state | Guarded by | Touched when |
|---|---|---|
| List of connected clients | Users lock | Someone joins, leaves, or a message goes out |
| Conversation history | History lock | A message arrives or a backup runs |
Final Solution
The final design and outcome
In a test session two clients join, exchange three messages, and leave. Each sees the other's messages and not an echo of its own, the server logs every connection and disconnection, and the backup file holds the full conversation in order. An alarm signal saves that file every 30 seconds, and stopping the server saves it once more.
(opens in a new tab)Impact & Validation
Results, learnings, and outcomes
The same accept loop, per-connection worker, and guarded shared state sit underneath every web server and API that came later in the program.




