Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Build a Real-Time Chat Room with Ktor

Build a multi-room chat with Ktor WebSockets. Design the message protocol, manage connections and rooms safely with coroutines, broadcast with SharedFlow, add history and test it. Includes a runnable core.

A chat room is the natural project for WebSockets. Many clients stay connected, any message from one must reach all the others in the room, and clients join and leave at any moment. That makes it a good test of coroutines, shared state and clean shutdown. In this project you design a small JSON protocol, build the room logic, then wire it to Ktor routes.

About the examples. The Ktor WebSocket code is real and read-only (the site cannot run Ktor). The room logic is plain Kotlin with coroutines, runnable here: each "connection" is a channel standing in for a WebSocket session, so you can watch messages flow between several simulated users.

1. The protocol

Decide the messages before writing code. Use JSON with a type field, so clients and server can add new kinds of messages later. Messages from the client:

JSON
{"type": "join",    "room": "general", "name": "ann"}
{"type": "say",     "text": "hello everyone"}
{"type": "leave"}

Messages from the server:

JSON
{"type": "joined",  "room": "general", "users": ["ann", "bob"], "history": [...]}
{"type": "message", "from": "bob", "text": "hi", "at": 1712345678}
{"type": "presence","user": "carl", "status": "online"}
{"type": "error",   "reason": "name already taken"}

In Kotlin, a sealed interface with @Serializable subclasses models this nicely, and the kotlinx.serialization polymorphism uses the type field as the discriminator (@SerialName("say")).

2. Design rules for the room

  • One owner for the state. A room has a set of members and a history. Many coroutines touch it (one per connection), so protect it. The simplest safe design is a single Mutex per room, or a single coroutine that owns the state and receives commands through a channel.
  • Slow clients must not slow the room. If one client's network is slow, sending to it must not block the others. Give every connection its own buffered outgoing channel and a sender coroutine, and disconnect a client whose buffer overflows.
  • Always clean up. When the socket closes (for any reason) remove the member and announce it, using finally.
  • Bound everything. Limit message length, history size and the rate of messages per user.

3. The room logic, runnable

The code below simulates connections with Channels. Room.join registers a member and returns the channel that carries that member's incoming messages. say broadcasts to everyone, keeps a bounded history, and drops members whose buffer is full.

Kotlin Core: rooms, broadcast, history and leave

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output from top to bottom: each user sees only the messages broadcast while they were a member, the late joiner gets the bounded history, and invalid actions are rejected with clear errors. Closing a member's channel on leave ends the listener loop, which is how cleanup propagates.

4. A broadcast hub with SharedFlow

Instead of a map of channels, Kotlin has a ready-made fan-out tool: MutableSharedFlow. Every collector receives every emitted value. A buffer with DROP_OLDEST protects the room from slow collectors. Many chat servers need nothing more than this:

Kotlin Core: SharedFlow as a room hub

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

replay = 2 gives a new subscriber the most recent two messages (bob sees "second", "third", then the live ones). For per-room history with names, presence and limits, the explicit Room class above is more flexible; for broadcasting alone, SharedFlow is shorter. The lesson Channels and Broadcasting compares these tools.

5. The Ktor WebSocket route

Each connected client runs one handler coroutine. Receiving and sending happen concurrently: one loop reads frames from the socket, another forwards the member's outbox to the socket.

Kotlin
fun Application.module() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 30.seconds
        maxFrameSize = 64 * 1024
        contentConverter = KotlinxWebsocketSerializationConverter(Json)
    }

    val rooms = RoomRegistry()

    routing {
        webSocket("/chat/{room}") {
            val room = rooms.get(call.parameters["room"]!!)
            var me: Member? = null
            try {
                val hello = receiveDeserialized<ClientMessage.Join>()
                me = try { room.join(hello.name) } catch (e: IllegalArgumentException) {
                    sendSerialized(ServerMessage.Error(e.message ?: "bad request"))
                    close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "join failed"))
                    return@webSocket
                }

                val sender = launch {
                    for (line in me.outbox) send(Frame.Text(line))     // outbox -> socket
                }
                try {
                    for (frame in incoming) {                           // socket -> room
                        if (frame is Frame.Text) room.say(me.name, frame.readText())
                    }
                } finally {
                    sender.cancel()
                }
            } finally {
                me?.let { room.leave(it.name) }                         // always runs
            }
        }
    }
}

Points to notice:

  • The finally block guarantees leave runs on normal close, network failure and server shutdown alike.
  • incoming is a channel of frames; the loop ends when the client closes.
  • pingPeriod and timeout detect half-dead connections, which happen constantly on mobile networks.
  • Authentication: browsers cannot set headers on a WebSocket, so authenticate before the upgrade (cookie or session) or send the token as the first message or a query parameter, and reject bad ones before join. See Sessions and Cookies and Bearer Tokens and JWT.

6. A browser client

A minimal page needs no framework:

HTML
<input id="msg"><button id="send">Send</button>
<ul id="log"></ul>
<script>
  const ws = new WebSocket(`ws://${location.host}/chat/general`);
  ws.onopen = () => ws.send(JSON.stringify({ type: "join", name: "guest" + Math.floor(Math.random() * 100) }));
  ws.onmessage = (e) => log.insertAdjacentHTML("beforeend", `<li>${e.data}</li>`);
  send.onclick = () => { ws.send(msg.value); msg.value = ""; };
</script>

When you render messages in the page, escape them (use textContent, not innerHTML); the template above is only a sketch and would be an XSS hole if a user sends <script>. Escaping on output is a client duty that the server cannot replace.

7. Testing

Ktor's test client can open WebSocket sessions without a network:

Kotlin
@Test
fun messagesReachOtherUsers() = testApplication {
    application { module() }
    val client = createClient { install(io.ktor.client.plugins.websocket.WebSockets) }

    client.webSocket("/chat/general") {
        send(Frame.Text("""{"type":"join","name":"ann"}"""))
        val welcome = (incoming.receive() as Frame.Text).readText()
        assertTrue("welcome" in welcome)
        send(Frame.Text("hi"))
        assertEquals("ann: hi", (incoming.receive() as Frame.Text).readText())
    }
}

For concurrent tests with several users, see Testing WebSockets, SSE and Concurrent Code.

Ideas to extend it

  • Private messages and typing indicators (new message types).
  • Persist history with Exposed and load the last 50 messages on join.
  • Scale across servers: a single in-memory hub only works on one instance, so use a message broker such as Redis pub/sub or NATS to fan out between instances.
  • Per-user message rate limits and moderation commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why give each connection its own buffered outgoing channel?

    Isolating the send path prevents a slow receiver from stalling the room.
  2. 2. Why remove the member in a finally block?

    Otherwise a crashed connection would remain in the room forever.
  3. 3. What does replay = 2 do on a MutableSharedFlow?

    Replay lets late subscribers catch up with recent values.
  4. 4. What is a limitation of an in-memory room hub when you run two server instances?

    State lives in one process; a broker is needed to connect instances.

Summary

  • Define a typed JSON protocol before coding; use a type discriminator.
  • Protect room state with a Mutex or a single owning coroutine; give each connection a bounded outbox.
  • Use finally for cleanup, ping and timeout for dead connections, and limits on size and rate.
  • MutableSharedFlow is a compact broadcast hub; escape messages when rendering in the browser.
  • Scale beyond one instance with an external broker.

Next: Project: A Task API with Auth and a Database