Build a concurrent TCP chat server
Build a chat server that broadcasts messages to many clients using epoll or a thread pool.
By Invicly Tech, , in Linux System Programming. About 15 minutes to read.
In short
A chat server ties together sockets, multiplexing, buffering and protocol design. Clients connect over TCP and send newline-terminated lines, and the server broadcasts each complete line to everyone else. The hard parts are partial reads, slow clients whose buffers fill up, and disconnects in the middle of a broadcast.
Explained simply
A chat server is a program that many people connect to at the same time. When one person sends a message, the server passes it to everyone else. You can test it with netcat (nc), a tool that opens a TCP connection and lets you type into it.
TCP gives you a stream of bytes, not separate messages. If a client sends hello and then world, your server might read helloworld in one go, or hel and then loworld. So you need a rule for where a message ends. The easiest rule is: every message ends with a newline character.
The server must never get stuck waiting for one client. A single thread with epoll can watch thousands of sockets and only touch the ones that are ready. Each client gets a small record with its socket, its nickname, and two buffers: bytes received but not yet a full line, and bytes waiting to be sent.
Most of the real work is in the unhappy cases: a client that disconnects in the middle of a message, a client that stops reading, a line that is far too long. Handling these well is what makes the project worth showing.
Press Play on a diagram to walk through it one step at a time.
- 1Clients
nc or a small C client, one TCP connection each.
- 2Listening socket
accept4 with SOCK_NONBLOCK for new clients.
- 3epoll event loop
One thread waits for readable or writable sockets.
- 4Connection table
Per-client fd, nickname, input and output buffers.
- 5Protocol handler
Splits lines, handles /nick and /quit, broadcasts.
- 1Socket readable
- 2Read until EAGAIN
- 3Extract complete lines
- 4Queue to other clients
Append to each output buffer.
- 5Flush on EPOLLOUT
Drop clients whose buffers overflow.
- No locks needed
- Handles thousands of idle clients
- Every call must be non-blocking
- One slow handler delays everyone
- Simple blocking read and write
- Shared client list needs a mutex
- Each thread reserves a stack (often 8 MiB virtual)
- Broadcast under a lock can block on a slow socket
In depth
Designing a small line protocol
Write the protocol down before you write code. A good first version: every message is UTF-8 text ending in \n, and the server also accepts \r\n because telnet and some clients send it. Lines longer than a fixed limit, say 512 bytes, are an error and the client is disconnected.
Lines starting with / are commands: /nick NAME sets a nickname, /who lists people, /quit leaves. Every other line is chat. The server answers with lines too: chat appears as [alice] hello, and server notices start with * so clients can tell them apart.
Decide the rules for nicknames: allowed characters, maximum length, what happens on a duplicate. Clear, strict rules are easier to test and harder to abuse. A client that can send any bytes can try to inject a fake [admin] line, so reject control characters.
- Max line length: reject, do not silently truncate
- Unique nicknames, letters, digits, - and _ only
- Server lines start with * for notices
- Server to alice (nc): * welcome, use /nick NAME1* welcome, use /nick NAME
- alice (nc) to Server: /nick alice2/nick alice
- Server to bob (nc): * alice joined3* alice joined
- alice (nc) to Server: hello everyone4hello everyone
- Server to bob (nc): [alice] hello everyone5[alice] hello everyone
- bob (nc) to Server: connection closed (read returns 0)6connection closed (read returns 0)
- Server to alice (nc): * bob left7* bob left
The epoll loop in practice
Create the listening socket with SO_REUSEADDR so you can restart the server right away, make it non-blocking, and add it to epoll. When it is readable, call accept4 with SOCK_NONBLOCK | SOCK_CLOEXEC in a loop until it fails with EAGAIN, because several clients may be waiting.
Store a pointer to the client record in event.data.ptr, so each event leads straight to its client. Level-triggered mode (the default) is simpler: epoll keeps reporting a socket while data remains. Edge-triggered mode (EPOLLET) reports only changes, so you must read until EAGAIN every time or the rest of the data waits forever.
Only ask for EPOLLOUT while a client's output buffer is not empty. A socket is almost always writable, so leaving EPOLLOUT on makes epoll_wait return at once, again and again, and the server burns 100 percent CPU doing nothing.
- Reports while data is still unread
- One read per event is fine
- Forgiving of small mistakes
- Best choice for a first server
- Reports only when new data arrives
- Must read until EAGAIN
- Fewer wakeups under heavy load
- Easy to lose data with a bug
Slow clients and the output buffer
send on a non-blocking socket may write only part of your data, or fail with EAGAIN when the kernel's send buffer is full. So never assume a broadcast is sent the moment you call send. Append the message to each client's output buffer, try to send what you can, and keep the rest for the next EPOLLOUT event.
A client that stops reading (for example a laptop that went to sleep) will fill its kernel buffer and then your buffer. Give each output buffer a hard limit, such as 64 KiB. When a new message would not fit, disconnect that client. One slow reader must never slow down or crash the whole room, and memory must never grow without limit.
Writing to a socket whose peer has gone raises SIGPIPE, and its default action kills your whole server. Send with the MSG_NOSIGNAL flag, or set SIGPIPE to SIG_IGN at startup, and handle the EPIPE error instead.
- Bounded buffer per client, disconnect on overflow
- MSG_NOSIGNAL on every send
- Count bytes dropped and clients kicked for your logs
Disconnects during a broadcast
A client can vanish at any moment: read returns 0 for a normal close, or read and send fail with ECONNRESET or EPIPE. The tricky part is when this happens in the middle of a loop over all clients, or in the middle of a batch of events from one epoll_wait call.
If you free the client record right away, a later event in the same batch may still hold a pointer to it, which is a use-after-free. Worse, the kernel may reuse the same fd number for a brand new client. The safe pattern is to mark the client as dead, skip dead clients for the rest of the batch, and free all dead clients after the batch ends.
Closing an fd removes it from epoll only when no other descriptor refers to the same open file. If you ever dup the fd or fork, call epoll_ctl with EPOLL_CTL_DEL explicitly before close.
- Seen on read
- read returns 0 (peer closed)
- ECONNRESET (peer reset)
- Seen on send
- EPIPE (peer gone)
- ECONNRESET
- Server decides
- Output buffer full
- Line too long
- Idle too long
- Server shutting down
Load testing and limits
A server that works with two clients can still fail at 2,000. Each connection uses one file descriptor, and the default soft limit is often 1024. Check it with ulimit -n, and raise it with ulimit -n in the shell, setrlimit in code, or LimitNOFILE= in a systemd unit. When accept fails with EMFILE, log it and keep running instead of exiting.
The listen backlog decides how many finished handshakes can wait for accept. The kernel caps it at net.core.somaxconn, which is 4096 by default since Linux 5.4, so listen(fd, SOMAXCONN) is a reasonable choice.
For tests, script many nc clients, plus a few nasty ones: a client that sends one huge line, one that connects and sends nothing, and one that never reads. Watch the server with ss -tn and top while the test runs, and check that memory stays flat.
- ss -s shows totals; ss -tn sport = :7000 shows each connection
- exec 3<>/dev/tcp/127.0.0.1/7000 in bash opens a client that never reads
Learn it in 5 short steps
About 2h each. Track them with a timer in your plan.
- 1Design a line-based chat protocol~2h
- 2Accept clients with an epoll event loop~2h
- 3Broadcast messages to all clients~2h
- 4Handle slow clients and disconnects~2h
- 5Load test with many netcat clients~2h
Key points
- Treat input as a byte stream and only act on complete lines.
- Give each client a bounded output buffer and disconnect clients that fall too far behind.
- Removing a client during a broadcast loop needs care: mark it, then clean up afterwards.
- An alternative design uses a thread per client and a mutex-protected client list.
Key terms
Tap a card to flip it. 0/5 known
Examples
make && ./chatd 7000 &
for i in $(seq 1 200); do (echo "/nick bot$i"; sleep 30) | nc localhost 7000 > /dev/null & done
nc localhost 7000 # type messages and watch them broadcast
ss -tn state established "( sport = :7000 )" | wc -l
valgrind --leak-check=full ./chatd 7000Load test with 200 netcat clients and count live connections.
Turning a byte stream into lines
Each client has a fixed array in[] and a count in_len. After every read, append the new bytes, then pull out every complete line with memchr. Whatever is left after the last newline is a partial line: move it to the front of the buffer and wait for more bytes. If the buffer is full and still has no newline, the line is too long and the client is marked for disconnect. This works no matter how TCP splits or joins the data.
/* c->in holds c->in_len bytes received so far */
char *start = c->in, *nl;
size_t left = c->in_len;
while ((nl = memchr(start, '\n', left)) != NULL) {
size_t len = (size_t)(nl - start);
if (len > 0 && start[len - 1] == '\r') len--; /* accept CRLF */
handle_line(c, start, len); /* may mark c->dead */
left -= (size_t)(nl - start) + 1;
start = nl + 1;
}
memmove(c->in, start, left); /* keep the partial line */
c->in_len = left;
if (c->in_len == sizeof c->in) c->dead = 1; /* line too long */Sending without ever blocking
flush_out sends as much of the output buffer as the kernel accepts. EINTR means try again, EAGAIN means the kernel buffer is full so stop for now, and any other error means the client is gone. Afterwards it turns EPOLLOUT on only if bytes are still waiting, which avoids a busy loop. To broadcast, append the line to every other live client's out[] (disconnecting anyone whose buffer would overflow) and call flush_out for each.
/* Send queued bytes without blocking. Returns -1 if the client must go. */
static int flush_out(int epfd, struct client *c) {
while (c->out_len > 0) {
ssize_t w = send(c->fd, c->out, c->out_len, MSG_NOSIGNAL);
if (w < 0 && errno == EINTR) continue;
if (w < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) break;
if (w < 0) return -1; /* EPIPE, ECONNRESET, ... */
memmove(c->out, c->out + w, c->out_len - (size_t)w);
c->out_len -= (size_t)w;
}
struct epoll_event ev = { .events = EPOLLIN | (c->out_len ? EPOLLOUT : 0),
.data.ptr = c };
return epoll_ctl(epfd, EPOLL_CTL_MOD, c->fd, &ev);
}Quick reference
- Act only on complete lines; keep the partial tail in the input buffer.
- accept4(lfd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC) in a loop until EAGAIN.
- Enable EPOLLOUT only while the output buffer has data, or the loop spins at 100% CPU.
- send(fd, buf, n, MSG_NOSIGNAL) turns a deadly SIGPIPE into an EPIPE error.
- Mark clients dead during a batch; free them after the epoll_wait batch is done.
- Check and raise the fd limit: ulimit -n, setrlimit(RLIMIT_NOFILE), or LimitNOFILE= in systemd.
- Count connections: ss -tn state established '( sport = :7000 )' | tail -n +2 | wc -l
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a /who command that sends the asking client one line listing all nicknames, like * online: alice bob carol.
- Exercise 2medium
Prove that one client that never reads cannot hurt the others. Open a non-reading client, flood the room from another client, and check that the server disconnects the slow one while normal clients keep chatting.
- Exercise 3hard
Shut down cleanly on SIGTERM or SIGINT: tell every client the server is going away, flush what you can, close all sockets, free memory, and exit 0, without any code in a signal handler.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use epoll or one thread per client?
- Both work for a chat server. epoll in one thread needs no locks and scales to many idle connections, while thread per client is easier to write but needs a mutex around the client list and more memory per connection. Building the epoll version teaches more about how real servers work.
- Why do I get Address already in use when I restart my server?
- The old connections are in the TIME_WAIT state for a while after the server exits. Set SO_REUSEADDR on the listening socket before bind and the restart will work at once.
- How do I test my chat server without writing a client?
- Use nc localhost 7000 in a few terminals and type. For load, start many nc processes from a shell loop, and use ss -tn to count the connections.
- Is level-triggered or edge-triggered epoll better?
- Start with level-triggered, the default, because it forgives a missed read. Edge-triggered can cut wakeups under heavy load, but you must drain every socket until EAGAIN.