WebSockets in Kotlin: From Theory to Real-Time Magic
Imagine opening a messenger, sending a message — and it instantly appears to the recipient. No page reload, no constant requests to the server. This isn't magic, it's WebSockets in Kotlin. If you've ever wanted to create your own chat, a real-time notification system, or a multiplayer game — you've come to the right place.
In this article, we'll break down how WebSockets work, write a full real-time application in Kotlin using Ktor, and I'll show you code you can run right away. Let's go!
What are WebSockets and Why Do You Need Them in Kotlin?
WebSocket is a protocol for bidirectional communication between a client and server over a single TCP connection. Unlike classic HTTP, where the client always initiates a request, WebSocket allows the server to send data to the client at any time.
Why is WebSocket Better than HTTP?
- Instant: data is delivered in milliseconds
- Bandwidth efficient: no extra headers like in HTTP
- Bidirectional: the server can initiate sending
- Persistent connection: no need to re-establish each time
Kotlin, with its coroutines and the Ktor framework, is ideal for working with WebSockets. Asynchrony, lightweight nature, and expressive syntax — that's what makes Kotlin WebSocket development so enjoyable.
When to Use WebSockets?
Here are several scenarios where real-time applications in Kotlin with WebSockets are indispensable:
- Chats and messengers — real-time message delivery
- Notification systems — alerts, pop-ups, status updates
- Online games — player synchronization
- Stock tickers — price updates without reloading
- Collaborative editing — Google Docs-like functionality
Project Setup: Ktor + WebSockets
To create a WebSocket server in Kotlin we will use Ktor — a modern asynchronous framework from JetBrains. Let's set up the project.
Step 1: Add Dependencies
If you're using Gradle (and I'm sure you are), add to build.gradle.kts:
dependencies { implementation("io.ktor:ktor-server-core:2.3.7") implementation("io.ktor:ktor-server-netty:2.3.7") implementation("io.ktor:ktor-server-websockets:2.3.7") implementation("ch.qos.logback:logback-classic:1.4.14")}Step 2: Create the WebSocket Server
Now let's write the server itself. It will accept connections and broadcast messages to all connected clients — basic chat logic.
import io.ktor.server.engine.*import io.ktor.server.netty.*import io.ktor.server.websocket.*import io.ktor.websocket.*import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.launch
fun main() { val clients = mutableSetOf<WebSocketSession>()
embeddedServer(Netty, port = 8080) { install(WebSockets) { pingPeriod = 15_000 // 15 seconds timeout = 15_000 maxFrameSize = Long.MAX_VALUE }
routing { webSocket("/chat") { // Add client clients.add(this) println("New connection: $this")
try { for (frame in incoming) { if (frame is Frame.Text) { val message = frame.readText() println("Received: $message")
// Send to all clients