WebSockets

suggest change

A WebSocket is a long-lived, full-duplex connection between a client and a server. It starts as an ordinary HTTP request with an Upgrade: websocket header. When the server answers 101 Switching Protocols, both sides can send messages (called frames) at any time, without the request/response cycle of plain HTTP.

WebSockets fit chat, live dashboards, multiplayer games, notifications and anything else where the server needs to push data to clients.

In Kotlin the most idiomatic choice is Ktor. It provides a WebSocket server and client built on coroutines, so a connection is just a suspending block of code. On the JVM you can also use OkHttp or the JDK's built-in java.net.http.WebSocket as a client.

All examples below were compiled with Kotlin 2.4.21 and Ktor 3.6.0.

Dependencies

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21" // only for JSON messages
}

val ktorVersion = "3.6.0"

dependencies {
    // server
    implementation("io.ktor:ktor-server-netty:$ktorVersion")
    implementation("io.ktor:ktor-server-websockets:$ktorVersion")
    // client
    implementation("io.ktor:ktor-client-cio:$ktorVersion")
    implementation("io.ktor:ktor-client-websockets:$ktorVersion")
    // JSON over WebSockets (optional)
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
    // tests
    testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
}

Frames

Inside a Ktor WebSocket session you work with these types:

Echo server and client

The program below starts a Netty server with an /echo endpoint. It then connects to the endpoint with the Ktor client from the same process:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.pingPeriod
import io.ktor.server.websocket.timeout
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.CloseReason
import io.ktor.websocket.Frame
import io.ktor.websocket.close
import io.ktor.websocket.readText
import io.ktor.websocket.send
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.seconds
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets

fun main() = runBlocking {
    val server = embeddedServer(Netty, port = 8080) {
        install(WebSockets) {
            pingPeriod = 15.seconds     // send Ping frames to keep the connection alive
            timeout = 15.seconds        // close if no Pong arrives in time
            maxFrameSize = 64 * 1024    // reject frames larger than 64 KB
            masking = false
        }
        routing {
            webSocket("/echo") {
                send("Welcome! Send me text, 'bye' to quit.")
                for (frame in incoming) {
                    if (frame !is Frame.Text) continue
                    val text = frame.readText()
                    if (text == "bye") {
                        close(CloseReason(CloseReason.Codes.NORMAL, "Client said bye"))
                    } else {
                        send("echo: $text")
                    }
                }
            }
        }
    }.start(wait = false)

    val client = HttpClient(CIO) { install(ClientWebSockets) }
    client.webSocket("ws://localhost:8080/echo") {
        println((incoming.receive() as Frame.Text).readText())
        for (msg in listOf("hello", "kotlin", "bye")) {
            send(msg)
        }
        for (frame in incoming) {
            if (frame is Frame.Text) println(frame.readText())
        }
        println("closed: ${closeReason.await()}")
    }
    client.close()
    server.stop(500, 1000)
}

Output:

Welcome! Send me text, 'bye' to quit.
echo: hello
echo: kotlin
closed: CloseReason(reason=NORMAL, message=Client said bye)

Things to notice:

Reading and writing at the same time

A WebSocket is full duplex, so the server often has to push data while it also listens for client commands. The usual pattern is to launch a writer coroutine and keep reading in the handler. The coroutine is a child of the session, so it is cancelled when the session ends.

Here every connected client receives each change of a StateFlow (see Flows). A client can send stop to end its subscription:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.CloseReason
import io.ktor.websocket.Frame
import io.ktor.websocket.close
import io.ktor.websocket.readText
import io.ktor.websocket.send
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets

fun main() = runBlocking {
    val price = MutableStateFlow(100)

    val server = embeddedServer(Netty, port = 8080) {
        install(WebSockets)
        routing {
            webSocket("/prices") {
                // writer: push every price change to this client
                val pusher = launch {
                    price.collect { send("price=$it") }
                }
                // reader: handle commands until the client goes away
                for (frame in incoming) {
                    if (frame is Frame.Text && frame.readText() == "stop") {
                        close(CloseReason(CloseReason.Codes.NORMAL, "stopped"))
                    }
                }
                pusher.cancel()
            }
        }
    }.start(wait = false)

    val client = HttpClient(CIO) { install(ClientWebSockets) }
    client.webSocket("ws://localhost:8080/prices") {
        var count = 0
        for (frame in incoming) {
            if (frame !is Frame.Text) continue
            println("client: ${frame.readText()}")
            count++
            if (count == 1) {
                // simulate a market feed once we're subscribed
                launch {
                    for (p in listOf(101, 99, 105)) {
                        delay(100)
                        price.value = p
                    }
                }
            }
            if (count == 4) send("stop")
        }
        println("client: ${closeReason.await()?.message}")
    }
    client.close()
    server.stop(500, 1000)
}

Output:

client: price=100
client: price=101
client: price=99
client: price=105
client: stopped

Interactive clients use the same pattern. One coroutine reads incoming and prints messages, while the main coroutine reads user input and calls send.

JSON messages and a chat room

Real protocols usually exchange structured messages. You can set a contentConverter on both plugins and then use sendSerialized / receiveDeserialized with any @Serializable class.

The chat room below keeps the open sessions in a ConcurrentHashMap. Each incoming message is broadcast to all members:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.websocket.receiveDeserialized
import io.ktor.client.plugins.websocket.sendSerialized
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.routing.routing
import io.ktor.server.websocket.DefaultWebSocketServerSession
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.receiveDeserialized
import io.ktor.server.websocket.sendSerialized
import io.ktor.server.websocket.webSocket
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.util.concurrent.ConcurrentHashMap
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets

@Serializable
data class ChatMessage(val from: String, val text: String)

class ChatRoom {
    private val members = ConcurrentHashMap<String, DefaultWebSocketServerSession>()

    suspend fun join(name: String, session: DefaultWebSocketServerSession) {
        members[name] = session
        broadcast(ChatMessage("server", "$name joined (${members.size} online)"))
    }

    suspend fun leave(name: String) {
        members.remove(name)
        broadcast(ChatMessage("server", "$name left"))
    }

    suspend fun broadcast(msg: ChatMessage) {
        for ((name, session) in members) {
            try {
                session.sendSerialized(msg)
            } catch (e: Exception) {
                members.remove(name) // dead connection
            }
        }
    }
}

fun main() = runBlocking {
    val json = Json { ignoreUnknownKeys = true }
    val room = ChatRoom()

    val server = embeddedServer(Netty, port = 8080) {
        install(WebSockets) {
            contentConverter = KotlinxWebsocketSerializationConverter(json)
        }
        routing {
            webSocket("/chat/{name}") {
                val name = call.parameters["name"]!!
                room.join(name, this)
                try {
                    while (true) {
                        val msg = receiveDeserialized<ChatMessage>()
                        room.broadcast(msg.copy(from = name))
                    }
                } catch (e: Exception) {
                    // ClosedReceiveChannelException when the client disconnects
                } finally {
                    room.leave(name)
                }
            }
        }
    }.start(wait = false)

    val client = HttpClient(CIO) {
        install(ClientWebSockets) {
            contentConverter = KotlinxWebsocketSerializationConverter(json)
        }
    }

    val bobReady = CompletableDeferred<Unit>()
    val bob = async {
        client.webSocket("ws://localhost:8080/chat/bob") {
            bobReady.complete(Unit)
            repeat(4) {
                val m = receiveDeserialized<ChatMessage>()
                println("bob got   [${m.from}] ${m.text}")
            }
        }
    }
    bobReady.await()
    delay(100)
    client.webSocket("ws://localhost:8080/chat/alice") {
        receiveDeserialized<ChatMessage>() // skip own "alice joined"
        sendSerialized(ChatMessage("ignored", "Hi Bob!"))
        val m = receiveDeserialized<ChatMessage>()
        println("alice got [${m.from}] ${m.text}")
    }
    bob.await()
    client.close()
    server.stop(500, 1000)
}

Output (the two Hi Bob! lines can appear in either order):

bob got   [server] bob joined (1 online)
bob got   [server] alice joined (2 online)
bob got   [alice] Hi Bob!
alice got [alice] Hi Bob!
bob got   [server] alice left

Notes:

Closing connections

Close codes are defined in CloseReason.Codes:

Code Name Meaning
1000 NORMAL Normal closure
1001 GOING_AWAY Server shutting down / page navigated away
1002 PROTOCOL_ERROR Protocol violation
1003 CANNOT_ACCEPT Unsupported data type
1008 VIOLATED_POLICY Policy violation (e.g. auth failed)
1009 TOO_BIG Message larger than maxFrameSize
1011 INTERNAL_ERROR Unexpected server error
webSocket("/admin") {
    val token = call.request.queryParameters["token"]
    if (token != System.getenv("ADMIN_TOKEN")) {
        close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "bad token"))
        return@webSocket
    }
    // ...
}

On the other side, read the code and message from closeReason.await().

Testing WebSocket endpoints

testApplication from ktor-server-test-host runs your module in memory, without opening a port. You get a client from createClient and install the client WebSockets plugin on it. The example below also shows binary frames:

import io.ktor.client.plugins.websocket.webSocket
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.routing.routing
import io.ktor.server.testing.testApplication
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.Frame
import io.ktor.websocket.readBytes
import io.ktor.websocket.readText
import io.ktor.websocket.send
import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets

fun Application.module() {
    install(WebSockets)
    routing {
        webSocket("/upper") {
            for (frame in incoming) {
                when (frame) {
                    is Frame.Text -> send(frame.readText().uppercase())
                    is Frame.Binary -> send(frame.readBytes().reversedArray())
                    else -> {}
                }
            }
        }
    }
}

fun main() = testApplication {
    application { module() }
    val client = createClient { install(ClientWebSockets) }

    client.webSocket("/upper") {
        send("hello")
        val reply = (incoming.receive() as Frame.Text).readText()
        check(reply == "HELLO")
        println("text reply: $reply")

        send(Frame.Binary(true, byteArrayOf(1, 2, 3)))
        val bytes = (incoming.receive() as Frame.Binary).readBytes()
        println("binary reply: ${bytes.toList()}")
    }
}

Output:

text reply: HELLO
binary reply: [3, 2, 1]

In a real project, put the body of main in a JUnit test function and use assertEquals (see JUnit).

Other JVM clients: OkHttp and java.net.http

If you already use OkHttp (common on Android), it has a callback-based WebSocket client. The JDK has had java.net.http.WebSocket since Java 11, which needs no dependencies at all. Both clients below talk to a Ktor echo server:

import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.routing.routing
import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
import io.ktor.websocket.send
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.net.URI
import java.net.http.HttpClient
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

fun okHttpDemo() {
    val client = OkHttpClient.Builder()
        .pingInterval(20, TimeUnit.SECONDS)
        .build()
    val done = CountDownLatch(1)
    val request = Request.Builder().url("ws://localhost:8080/echo").build()

    client.newWebSocket(request, object : WebSocketListener() {
        override fun onOpen(webSocket: WebSocket, response: Response) {
            println("okhttp: open, HTTP ${response.code}")
            webSocket.send("ping from OkHttp")
        }
        override fun onMessage(webSocket: WebSocket, text: String) {
            println("okhttp: received '$text'")
            webSocket.close(1000, "done")
        }
        override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            webSocket.close(code, reason)
        }
        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            println("okhttp: closed $code $reason")
            done.countDown()
        }
        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            println("okhttp: failure $t")
            done.countDown()
        }
    })
    done.await(5, TimeUnit.SECONDS)
    client.dispatcher.executorService.shutdown()
    client.connectionPool.evictAll()
}

fun jdkDemo() {
    val received = CompletableFuture<String>()
    val listener = object : java.net.http.WebSocket.Listener {
        private val buffer = StringBuilder()
        override fun onText(ws: java.net.http.WebSocket, data: CharSequence, last: Boolean): CompletionStage<*>? {
            buffer.append(data)          // a message may arrive in several parts
            if (last) {
                received.complete(buffer.toString())
                buffer.setLength(0)
            }
            ws.request(1)                // ask for the next message
            return null
        }
    }
    val ws = HttpClient.newHttpClient().newWebSocketBuilder()
        .buildAsync(URI.create("ws://localhost:8080/echo"), listener)
        .join()
    ws.sendText("ping from java.net.http", true).join()
    println("jdk: received '${received.get(5, TimeUnit.SECONDS)}'")
    ws.sendClose(java.net.http.WebSocket.NORMAL_CLOSURE, "done").join()
}

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        install(WebSockets)
        routing {
            webSocket("/echo") {
                for (frame in incoming) {
                    if (frame is Frame.Text) send("echo: ${frame.readText()}")
                }
            }
        }
    }.start(wait = false)

    okHttpDemo()
    jdkDemo()
    server.stop(500, 1000)
}

Output:

okhttp: open, HTTP 101
okhttp: received 'echo: ping from OkHttp'
okhttp: closed 1000 done
jdk: received 'echo: ping from java.net.http'

OkHttp needs com.squareup.okhttp3:okhttp:5.5.0. Its listener methods run on OkHttp's own threads. In an Android app, switch to the main thread before you update the UI.

Practical tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents