Kotlin WebSocket Library: Ktor WebSocket
WebSocket is a protocol that provides a persistent bidirectional connection between a client and a server. In the Kotlin ecosystem, one of the most powerful and popular libraries for working with WebSocket is Ktor — an asynchronous framework created by JetBrains. Ktor provides full WebSocket support both on the server side and on the client side, allowing you to easily create real-time applications: chats, notifications, online games, data trackers, and much more.
In this article, we will take a detailed look at how to use WebSocket in Kotlin with Ktor. You will learn how to configure dependencies, create a WebSocket server and client, send and receive messages, as well as handle errors and connection closure.
Installation and Setup
To get started, add the necessary dependencies to the build.gradle.kts (or build.gradle) file. If you are using Gradle, include the following modules:
// build.gradle.ktsdependencies { // Server side implementation("io.ktor:ktor-server-core:2.3.0") implementation("io.ktor:ktor-server-netty:2.3.0") implementation("io.ktor:ktor-server-websockets:2.3.0")
// Client side implementation("io.ktor:ktor-client-core:2.3.0") implementation("io.ktor:ktor-client-cio:2.3.0") implementation("io.ktor:ktor-client-websockets:2.3.0")}For Maven, use similar artifacts. All Ktor modules version 2.x.x support Kotlin Coroutines and work on JVM, Android, iOS, and other platforms.
Creating a WebSocket Server with Ktor
Let's write a simple echo server that receives messages from the client and sends them back. The server will listen on port 8080.
import io.ktor.server.engine.*import io.ktor.server.netty.*import io.ktor.server.websocket.*import io.ktor.websocket.*import kotlinx.coroutines.*
fun main() { embeddedServer(Netty, port = 8080) { install(WebSockets) routing { webSocket("/chat") { send("Welcome to the chat!") for (frame in incoming) { if (frame is Frame.Text) { val text = frame.readText() println("Received: $text") send("Echo: $text") } } } } }.start(wait = true)}In this example:
install(WebSockets)— enables the WebSocket plugin on the server.webSocket("/chat")— defines the endpoint for connections.send()— sends a message to the client.incoming— the channel through which frames arrive from the client.- Frames can be text (
Frame.Text), binary (Frame.Binary), or control frames.
Creating a WebSocket Client with Ktor
Now let's write a client that connects to our server, sends a greeting, and reads the responses.
import io.ktor.client.*import io.ktor.client.engine.cio.*import io.ktor.client.plugins.websocket.*import io.ktor.websocket.*import kotlinx.coroutines.*
suspend fun main() { val client = HttpClient(CIO) { install(WebSockets) }
client.webSocket("ws://localhost:8080/chat") { // Read the welcome message val welcome = incoming.receive() as Frame.Text println("Server: ${welcome.readText()}")
// Send a message send(Frame.Text("Hello, server!"))
// Wait for the echo response val response = incoming.receive() as Frame.Text println("Server: ${response.readText()}")
// Close the connection close() }
client.close()}The client uses tw
Also in library
ORM for C++: Comparison and Usage Examples (ODB, SOCI, SQLiteCpp)
WorkManager for Kotlin: Complete Guide with Examples
Puppeteer for JavaScript (Node.js): Complete Guide with Examples
Dependency Injection Containers in Rust: Overview and Implementation Using "dicy" as an Example
Redis Client for PHP: Predis and PhpRedis – Connection and Examples