Skip to content
pri12ya871Public

About

Real-time chat API with rooms, presence and history, over a WebSocket implementation written from scratch. One runtime dependency.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

chat-api

A real-time chat server with rooms, presence, typing indicators and message history — over a WebSocket implementation written from scratch. No ws, no socket.io: the handshake, the frame codec, fragmentation, ping/pong and the closing handshake are all in src/ws/.

One runtime dependency: Express, and only for the REST routes and static files.

Node Express Tests License

Deploy to Render

On the hosted demo: Render's free plan proxies WebSockets, and this service keeps no disk state, so nothing is lost by the ephemeral filesystem. It does spin down after ~15 minutes idle — the first visit then waits ~50s for a cold start, and open connections are dropped when it sleeps. Reconnect handles that.

Quick start

npm install
npm start

Open http://localhost:4200 in two browser windows and talk to yourself.

Command What it does
npm start Serve on :4200
npm run dev Same, with --watch
npm test 58 tests, no framework

Protocol

Connect to ws://localhost:4200/?name=priya. Everything is JSON.

Client → server

{"type": "join",    "room": "general"}
{"type": "leave",   "room": "general"}
{"type": "message", "room": "general", "text": "hello"}
{"type": "typing",  "room": "general", "isTyping": true}

Server → client — welcome, joined (member list + history), left, presence (join/leave + updated members), message, typing, error.

REST, read-only — posting happens over the socket so membership and rate limits have one enforcement point:

Method Route Purpose
GET /api/rooms Active rooms with member and message counts
GET /api/rooms/:room/messages Recent history for a room
GET /health Live connection and room counts

Why write the WebSocket layer by hand

Because "real-time chat" built on socket.io is a project about socket.io. The protocol is small enough to implement and interesting enough to be worth understanding:

byte 0:  FIN(1) RSV(3) opcode(4)
byte 1:  MASK(1) payload-length(7)
then:    extended length  — 2 bytes if len == 126, 8 bytes if len == 127
then:    masking key      — 4 bytes, client-to-server only
then:    payload          — XORed with the masking key

Details that turned out to matter:

TCP has no message boundaries. One frame can arrive split across several data events and several frames can arrive in one. FrameDecoder buffers and only emits whole frames. There is a test that pushes a frame one byte at a time and asserts nothing decodes until the last one — the naive version that decodes straight from each chunk passes every hand test and then fails under load, which is a miserable way to find out.

Unmasking has to copy first. The payload is a subarray — a view onto the shared buffer — so XORing in place corrupts the bytes of the next frame in the same chunk. There is a regression test for exactly that.

Masking is one-directional. Client frames must be masked, server frames must not be. Masking exists so malicious JavaScript can't make a proxy misread a frame as an HTTP request, which is only a risk browser-to-server. An unmasked client frame closes the connection with 1002.

Length must use its smallest form, and the limit is checked from the declared length before any body is buffered — otherwise a client can announce 4GB and have the server hold it.

Two bugs worth reading about

Both were found by running the thing, not by the tests, and both are the kind that only appear in production.

1. Vanished clients became ghosts. Node leaves an upgraded socket half-open: when a peer disappears the socket emits end and then sits there — readable side finished, still writable — and close never fires. The connection stayed in every room it had joined as a member nobody could reach.

before fix:  t=1ms socket "end"        t=3000ms  conns=2  members=2   (never cleaned up)
after fix:   t=1ms socket "end"+"close"  t=200ms  conns=1  members=1   (leave broadcast sent)

Half-open has no meaning for a WebSocket, so the peer's FIN now ends the connection. Before the fix the 30-second heartbeat was the only thing that would eventually notice — a half-minute of a room showing people who had already left.

2. The first frame could be silently dropped. Node's upgrade event hands over a third argument, head — bytes it read past the request headers. A fast client that writes its first frame in the same TCP segment as the handshake has that frame in head, and ignoring it loses the message. It reproduces only under timing you won't see on a quiet laptop.

Other decisions

Two indexes of one relationship. The hub keeps room -> connections and connection -> rooms. Broadcasting needs the first, disconnecting needs the second, and a disconnect that scans every room to clean up is how a server with many rooms falls over.

History is a bounded ring buffer. An unbounded array is a memory leak with a long fuse — it only kills a process that runs long enough, which means production. Durable history is a database's job.

Rate limiting per connection. A socket delivers messages far faster than HTTP, so one client can flood everyone in a room. Over the limit gets an error frame, not a disconnect — clients that get dropped for typing fast reconnect in a loop.

Membership is the authorisation check. Without it anyone could post into any room by naming it, having never joined.

Presence is announced before membership is dropped, otherwise the broadcast has nobody left to tell.

Testing

58 tests via node --test. The integration suite includes a WebSocket client written for the tests — deliberately not built on the server's own decoder, since a shared bug would then be invisible to both sides. It masks its own frames, verifies the Sec-WebSocket-Accept value independently, and can send deliberately malformed bytes.

Covered: every payload-length boundary (0, 125, 126, 127, 65535, 65536), frames split byte-by-byte across chunks, several frames in one chunk, reserved bits, fragmented and oversized control frames, multi-byte UTF-8 through masking, room isolation, posting without joining, abrupt disconnects, fragmented application messages, flood limiting, and the RFC 6455 handshake example.

Also verified against real browser WebSocket clients, which are far stricter than any hand-written test client:

  • handshake accepted, two clients exchanging messages with live presence
  • 400-character messages exercising the 16-bit extended length path
  • नमस्ते 🙂 こんにちは round-tripping through masking intact
  • protocol errors returned as error frames without dropping the connection
  • graceful close reporting 1000, not 1006 — the browser only reports 1000 when the server completes the closing handshake correctly
  • a connection surviving five heartbeat sweeps and still delivering messages
npm test

Layout

src/
  ws/       frames.js (codec), handshake.js, connection.js, server.js
  chat/     hub.js (rooms + fan-out), history.js, protocol.js (validation)
  app.js    REST routes            server.js  http + ws on one port
public/     demo UI, no build step
test/       frames, handshake, hub, integration + a hand-written WS client

Known limits

  • No authentication. Names come from a query parameter and are cosmetic. The hook belongs in the upgrade handler — verify a token there and reject before the socket is created. It composes with auth-service, which issues them.
  • Single process. Rooms live in memory, so two instances don't share them. Scaling out needs a Redis pub/sub fan-out between nodes.
  • History is in memory and dies with the process.
  • No compression (permessage-deflate is unimplemented) and no Sec-WebSocket-Protocol negotiation.

License

MIT

About

Real-time chat API with rooms, presence and history, over a WebSocket implementation written from scratch. One runtime dependency.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages