Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท WebSockets and SSE

WebSockets in Ktor - Sessions, Frames and Echo Server

Build two-way real-time features with Ktor WebSockets. Install the plugin, handle text and binary frames, read incoming messages, close sessions cleanly, and practise with runnable Kotlin.

HTTP is a question and answer protocol: the client asks, the server replies, and the exchange is over. That is a poor fit for a chat room, a live scoreboard or a multiplayer game, where the server must send data when something happens, and the client also needs to send small messages often. A WebSocket is a long-lived two-way connection. It starts as a normal HTTP request (the "upgrade"), and after that both sides can send frames to each other at any time until one of them closes.

Ktor models a WebSocket as a coroutine with two channels: incoming (frames from the client) and outgoing (frames to the client). If you know Kotlin channels, you already know the heart of this lesson.

Install the plugin

Kotlin
dependencies {
    implementation("io.ktor:ktor-server-websockets:$ktorVersion")
}

fun Application.module() {
    install(WebSockets) {
        pingPeriod = 15.seconds       // keep-alive pings
        timeout = 15.seconds          // close if no pong arrives
        maxFrameSize = Long.MAX_VALUE
        masking = false
    }
    routing {
        webSocket("/echo") {
            send("Connected. Say something!")
            for (frame in incoming) {
                if (frame is Frame.Text) {
                    val text = frame.readText()
                    send("You said: $text")
                }
            }
        }
    }
}

All the code in this lesson that uses install and routing is real Ktor and read-only here. The runnable examples after it mimic the same session model.

What happens in a webSocket block

  • The block starts when a client completes the upgrade and is the session. It runs in its own coroutine; one block per connection.
  • incoming is a ReceiveChannel<Frame>. The for loop suspends until a frame arrives and ends when the connection closes.
  • send(...) puts a frame on outgoing. It suspends if the buffer is full, so a slow client applies back pressure.
  • When the block returns (or throws), Ktor closes the connection with a normal close frame.

Frame types

Frame Use
Frame.Text UTF-8 text, usually JSON
Frame.Binary Raw bytes (images, protobuf)
Frame.Ping / Frame.Pong Keep-alive; the plugin handles them for you
Frame.Close The end of the conversation, with a code and reason

Most real protocols send JSON text frames. Parse them with the same kotlinx.serialization setup you use for HTTP:

Kotlin
webSocket("/chat") {
    for (frame in incoming) {
        frame as? Frame.Text ?: continue
        val message = Json.decodeFromString<ChatMessage>(frame.readText())
        sendSerialized(message.copy(text = message.text.uppercase()))
    }
}

sendSerialized and receiveDeserialized become available when you configure contentConverter = KotlinxWebsocketSerializationConverter(Json) in the plugin. It is the same serialization setup you use for HTTP bodies.

A runnable model of a session

The code below imitates the two channels and the "server block runs per connection" model with ordinary Kotlin coroutines. Frame is our own small sealed class here, not Ktor's.

Kotlin Stand-in: an echo session with incoming and outgoing channels

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.

The server side is one coroutine that loops over incoming; the "client" in main pushes frames and prints what comes back. Nothing here polls: every side suspends until there is something to do, which is why a single JVM can hold tens of thousands of idle sockets.

Handling disconnects and errors

Networks drop connections without warning. In a Ktor block a vanished client shows up as the incoming loop ending (normal close) or as a ClosedReceiveChannelException / CancellationException thrown from incoming.receive() or send. Use try/finally to clean up state that belongs to the session, such as removing the user from a room:

Kotlin
webSocket("/room/{name}") {
    val user = Connection(this)
    rooms.getOrPut(call.parameters["name"]!!) { mutableSetOf() } += user
    try {
        for (frame in incoming) { /* ... */ }
    } catch (e: Exception) {
        application.log.warn("socket error: ${e.message}")
    } finally {
        rooms[call.parameters["name"]!!]?.remove(user)    // always runs
    }
}

To close deliberately from the server, call close(CloseReason(CloseReason.Codes.NORMAL, "bye")). Useful codes are NORMAL, GOING_AWAY, VIOLATED_POLICY (for example a failed auth) and TOO_BIG (message too large).

Kotlin Stand-in: cleanup in finally when a client vanishes

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.

Bo's failure did not affect Ann: each connection is an independent coroutine with its own finally. That isolation is the biggest practical benefit of structuring sockets this way.

Security and limits

  • Authenticate before upgrading. Browsers cannot set an Authorization header on a WebSocket, so use a cookie session, a short-lived token in the query string, or authenticate with the first message. Wrap the route in authenticate { webSocket(...) { } } (the Authentication chapter covers the plugins).
  • Validate every frame. Treat it like request input: size, shape and rate.
  • Check the Origin header if cookies authenticate the socket, to avoid cross-site WebSocket hijacking.
  • Set maxFrameSize to something realistic and add per-connection rate limits.
  • Behind a proxy (nginx, a load balancer), allow Upgrade headers and increase idle timeouts, or connections will drop after a minute.

Next you will make many sockets talk to each other in channels and broadcasting; for one-way streaming from server to browser there is a simpler tool, server-sent events.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a Ktor WebSocket route handle one connection?

    Each upgraded connection runs the route block as a separate coroutine, so clients are independent.
  2. 2. Why use try/finally in a WebSocket block?

    finally runs on normal close, errors and cancellation, so you can remove the user from rooms.
  3. 3. A browser cannot set custom headers on a WebSocket. How can you authenticate?

    Cookies and short-lived tokens are the usual approaches.
  4. 4. What does for (frame in incoming) do when the client closes the connection?

    The incoming channel closes, so the loop finishes normally.

Summary

  • A WebSocket is a long-lived two-way connection that begins as an HTTP upgrade.
  • Ktor runs each connection as a coroutine with incoming and outgoing frame channels.
  • Use text frames with JSON, handle close and failures with finally, and authenticate before or at the first message.
  • Configure ping, timeout and frame size, and allow upgrades in proxies.

Next: Server-Sent Events