Kotlin WebSocket library: ktor-client-websockets
In modern web development, real-time data exchange is increasingly required: online chats, notifications, stock quotes, multiplayer games. For Kotlin, one of the most powerful and native libraries for working with the WebSocket protocol is ktor-client-websockets — part of the Ktor ecosystem (Kotlin HTTP client).
In this article, we will thoroughly examine how to connect and use WebSocket in Kotlin using Ktor. You will learn how to install the library, establish a connection, send and receive messages, as well as handle errors and connection closure.
What is WebSocket and why is it needed?
WebSocket is a protocol that provides a persistent two-way connection between a client (for example, an Android application or a server) and a server. Unlike HTTP, where the client initiates a request each time, WebSocket allows the server to send data to the client instantly as soon as it appears. This is ideal for:
- chats and messengers;
- notifications and event feeds;
- games and collaborative editors;
- financial tickers and trading.
Installing the ktor-client-websockets library
To get started, add the dependency to your build.gradle.kts (Kotlin/JVM or Kotlin Multiplatform project).
// build.gradle.ktsdependencies { implementation("io.ktor:ktor-client-core:2.3.7") implementation("io.ktor:ktor-client-cio:2.3.7") // or another engine implementation("io.ktor:ktor-client-websockets:2.3.7")}If you are using Kotlin Multiplatform, make sure to add the module for each platform (for example, ktor-client-okhttp for Android).
Creating a WebSocket client
The main class for working with WebSocket is HttpClient with the WebSockets plugin. Let's look at the simplest example of connecting to a WebSocket server.
import io.ktor.client.*import io.ktor.client.plugins.websocket.*import io.ktor.websocket.*
suspend fun main() { val client = HttpClient { install(WebSockets) }
client.webSocket("ws://echo.websocket.org") { // Send a message send(Frame.Text("Hello, WebSocket!"))
// Receive the response for (frame in incoming) { when (frame) { is Frame.Text -> { println("Received: ${frame.readText()}") } else -> println("Other frame type: $frame") } } }
client.close()}In this code we:
- Create an HTTP client with WebSocket support.
- Establish a connection to the test server
ws://echo.websocket.org. - Send a text message.
- Read incoming frames and output them to the console.
Error handling and connection closure
In real applications, it is important to properly handle exceptions and close the connection. Use try-catch and finally.
import io.ktor.client.*import io.ktor.client.plugins.websocket.*import io.ktor.websocket.*import kotlinx.coroutines.*
suspend fun main() = coroutineScope { val client = HttpClient { install(WebSockets) }
try { client.webSocket("ws://your-server.com/ws") { // Sending send(Frame.Text("Ping"))
// Receiving with timeout withTimeout(5000) { for (frame in incoming) { if (frame is Frame.Text) { println("Response: ${frame.readText()}") } } } } } catch (e: Exception) { println("WebSocket error: ${e.message}") } finally { cli Also in library
Working with XML in Kotlin: Libraries and Tools for Parsing and Creation
gRPC for C++: Libraries, Examples, and Usage Guide
OAuth Client for C# (.NET): Implementing Authorization via Third-Party Services
NodaTime C# (.NET) Guide: Complete Tutorial with Examples