Skip to content
Sockets: A Multi-Client Chat Server

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.

SocketsTCPNetworkingThreadsPython

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.

The handler for one client: read the name, add the client to the shared list under the lock, and tell the newcomer who is already there.
Every message goes into the history, then out to each client except the one who sent it.

What the server keeps, and what guards it

Shared stateGuarded byTouched when
List of connected clientsUsers lockSomeone joins, leaves, or a message goes out
Conversation historyHistory lockA 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.

Terminal output of the chat server during a two-client session (opens in a new tab)
The server's view of the test session: two connections, three messages, two departures, and a backup on shutdown.
The first client learns it is alone, then sees the second arrive and reply.
The second client gets the list of who is in the room and sees the first one leave.
The backup file holds the whole conversation in order, including who joined and who left.

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.