This is a small non-blocking TCP chat server in C.
It listens on 127.0.0.1 and allows multiple clients to communicate with each other using socket multiplexing via select().
-
Let multiple clients connect to my server on 127.0.0.1 (localhost) on a specific port.
-
Give each client a unique ID.
-
Allow clients to send messages to the server.
-
The server broadcast messages to all other clients in real time.
-
Inform clients when someone arrives or leaves.
-
Handle multiple clients without using threads (via
select()).
-
Low-level network programming in C (sockets, TCP/IP).
-
Event-driven programming using select() instead of threads.
-
Buffering and handling partial messages (clients can send messages in chunks).
-
Non-blocking I/O and why monitoring read/write readiness is important.
-
Chat apps, game servers, or real-time services work behind the scences.
+--------------------+
| socket / bind / |
| listen |
+--------------------+
|
v
+--------------------+
| Start Server |
+--------------------+
|
v
+--------------------+
| Main Loop |
| select() |
+--------------------+
/ \
/ \
+----------------+ +--------------------+
| New connection | | Client socket ready|
| (listen fd) | | (recv/send) |
+----------------+ +--------------------+
| |
v v
+--------------------+ +----------------------+
| - accept() client | | recv() message |
| - assign ID | | or detect disconnect |
+--------------------+ +----------------------+
| | |
v v v
+------------------------- + +-------------------+ +-------------------+
| Notify other | | broadcast message | | If disconnected: |
| clients | | to | | - close fd |
| "client X just arrived" | | other clients | | - notify clients |
+--------------------------+ +-------------------+ +-------------------+
accept(), atoi(), bind(), close(), exit(), listen(), memcpy(), memset(), recv(), select(), socket(), strlen(), write().
An Http server will depend on sockets to transfer the requests & responses between the client and the server, so understanding how Tcp works behind the scenes is considered a foundational step toward understanding and building HTTP servers.
By working with raw TCP sockets, you gain hands-on experience with:
- Socket Programming: Learn how to create, bind, listen, and accept connections.
- Multiplexing: Use
select()to handle multiple clients simultaneously, a core concept for scalable servers. - Message Framing: Understand how to parse and assemble messages, which is essential for handling HTTP requests and responses.
- Client Management: Track connected clients, manage their state, and broadcast messages—skills directly transferable to HTTP session handling.
cc -Wall -Wextra -Werror tcp_server.c -o tcp_server && ./tcp_server <port>
You can open a client on the server using nc(netcat):
nc 127.0.0.1 8080
Open multiple terminals to simulate multiple clients.
Now type a message from a client — it gets broadcasted to the other clients, enjoy ;).
