WebSockets

Estimated reading time: 1 minute

This feature is defined in the class io.ktor.client.features.websocket.WebSockets in the artifact io.ktor:ktor-client-websocket:$ktor_version,io.ktor:ktor-client-cio:$ktor_version.
dependencies { compile "io.ktor:ktor-client-websocket:$ktor_version" compile "io.ktor:ktor-client-cio:$ktor_version" }
dependencies { compile("io.ktor:ktor-client-websocket:$ktor_version") compile("io.ktor:ktor-client-cio:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websocket</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websocket</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Ktor provides a WebSocket client only supporting the CIO engine in addition to supporting WebSockets at server side.

Once connected, client and server WebSockets share the same WebSocketSession interface for communication.

Right now, client WebSockets are only available for the CIO Client Engine.

The basic usage to create a http client supporting WebSockets is pretty simple:

val client = HttpClient(CIO).config { install(WebSockets) }

Once created we can perform a request, starting a WebSocketSession:

client.ws(method = HttpMethod.Get, host = "127.0.0.1", port = 8080, path = "/route/path/to/ws") { // this: DefaultClientWebSocketSession
    send(Frame.Text("Hello World"))

    for (message in incoming.map { it as? Frame.Text }.filterNotNull()) {
        println(message.readText())
    }
}

You can configure timeout and ping periods:

client.ws(...) { // this: DefaultClientWebSocketSession
    timeout = Duration.ofMinutes(10)
    pingInterval = Duration.ofMinutes(10) // null to disable it
}