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-websockets:$ktor_version,io.ktor:ktor-client-cio:$ktor_version,io.ktor:ktor-client-js:$ktor_version,io.ktor:ktor-client-okhttp:$ktor_version.
dependencies { implementation "io.ktor:ktor-client-websockets:$ktor_version" implementation "io.ktor:ktor-client-cio:$ktor_version" implementation "io.ktor:ktor-client-js:$ktor_version" implementation "io.ktor:ktor-client-okhttp:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-websockets:$ktor_version") implementation("io.ktor:ktor-client-cio:$ktor_version") implementation("io.ktor:ktor-client-js:$ktor_version") implementation("io.ktor:ktor-client-okhttp:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-websockets</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Ktor provides a WebSocket client for the following engines: CIO, OkHttp, Js. To get more information about the server side, follow this section.

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

The basic usage to create an HTTP client supporting WebSockets is pretty simple:

val client = HttpClient {
    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 text frame.
    send("Hello, Text frame")

    // Send text frame.
    send(Frame.Text("Hello World"))

    // Send binary frame.
    send(Frame.Binary(...))

    // Receive frame.
    val frame = incoming.receive()
    when (frame) {
        is Frame.Text -> println(frame.readText())
        is Frame.Binary -> println(frame.readBytes())
    }
}

For more information about the WebSocketSession, check the WebSocketSession page and the API reference.