Producing Kotlin Ktor WebSocket boilerplate
Prepared a complete Kotlin Ktor example implementing WebSockets with the actor model: a broadcast actor managing clients and per-client actors sending messages concurrently. The snippet includes defining broadcast events, creating actors, integrating with Ktor's WebSocket route, and starting an embedded Netty server.
Below is a minimal, single–file boilerplate that wires up Ktor + WebSockets using the actor model.
Each connection gets its own client actor (to push messages to that socket), and a single broadcast actor keeps track of active clients and fans out messages to them.
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import java.time.Duration
// Messages handled by the broadcast actor
sealed class BroadcastMsg {
data class Join(val client: SendChannel<String>) : BroadcastMsg()
data class Leave(val client: SendChannel<String>) : BroadcastMsg()
data class Broadcast(val text: String) : BroadcastMsg()
}
// Creates a client actor that delivers Strings to the WebSocket session
private fun CoroutineScope.clientActor(
session: DefaultWebSocketServerSession
): SendChannel<String> = actor(capacity = Channel.UNLIMITED) {
for (msg in channel) {
try {
session.send(Frame.Text(msg))
} catch (e: Throwable) {
// This will cause the actor to exit, and cleanup will occur in the route
close(e)
}
}
}
// Single broadcast actor for all clients
private fun CoroutineScope.broadcastActor(): SendChannel<BroadcastMsg> = actor(capacity = Channel.UNLIMITED) {
val clients = mutableSetOf<SendChannel<String>>()
for (msg in channel) {
when (msg) {
is BroadcastMsg.Join -> clients += msg.client
is BroadcastMsg.Leave -> {
clients -= msg.client
msg.client.close()
}
is BroadcastMsg.Broadcast -> {
// push concurrently
clients.forEach { client ->
launch { client.send(msg.text) }
}
}
}
}
}
fun Application.module() {
install(WebSockets) {
pingPeriod = Duration.ofSeconds(30)
timeout = Duration.ofSeconds(60)
}
// Application-wide broadcast actor
val broadcaster = CoroutineScope(Dispatchers.Default).broadcastActor()
routing {
webSocket("/ws") {
// Create client actor tied to this session
val client = CoroutineScope(Dispatchers.IO).clientActor(this)
broadcaster.send(BroadcastMsg.Join(client))
try {
send("Welcome! Type anything to broadcast to all connected clients.")
for (frame in incoming) {
val text = (frame as? Frame.Text)?.readText() ?: continue
// Broadcast what we received to everyone (including ourselves)
broadcaster.send(BroadcastMsg.Broadcast(text))
}
} finally {
// On close/error, remove this client
broadcaster.send(BroadcastMsg.Leave(client))
}
}
}
}
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
Gradle dependencies (Kotlin DSL)
dependencies {
implementation("io.ktor:ktor-server-core-jvm:<ktor_version>")
implementation("io.ktor:ktor-server-netty-jvm:<ktor_version>")
implementation("io.ktor:ktor-server-websockets-jvm:<ktor_version>")
implementation("ch.qos.logback:logback-classic:<logback_version>")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<coroutines_version>")
}
Run the server, then connect via ws://localhost:8080/ws in a WebSocket client. Each message from any connected client is broadcast to all others through the broadcast actor.