WebSockets

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.

  1. dependencies {
  2. implementation "io.ktor:ktor-client-websockets:$ktor_version"
  3. implementation "io.ktor:ktor-client-cio:$ktor_version"
  4. implementation "io.ktor:ktor-client-js:$ktor_version"
  5. implementation "io.ktor:ktor-client-okhttp:$ktor_version"
  6. }
  1. dependencies {
  2. implementation("io.ktor:ktor-client-websockets:$ktor_version")
  3. implementation("io.ktor:ktor-client-cio:$ktor_version")
  4. implementation("io.ktor:ktor-client-js:$ktor_version")
  5. implementation("io.ktor:ktor-client-okhttp:$ktor_version")
  6. }
  1. <project>
  2. ...
  3. <dependencies>
  4. <dependency>
  5. <groupId>io.ktor</groupId>
  6. <artifactId>ktor-client-websockets</artifactId>
  7. <version>${ktor.version}</version>
  8. <scope>compile</scope>
  9. </dependency>
  10. <dependency>
  11. <groupId>io.ktor</groupId>
  12. <artifactId>ktor-client-websockets</artifactId>
  13. <version>${ktor.version}</version>
  14. <scope>compile</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>io.ktor</groupId>
  18. <artifactId>ktor-client-websockets</artifactId>
  19. <version>${ktor.version}</version>
  20. <scope>compile</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>io.ktor</groupId>
  24. <artifactId>ktor-client-websockets</artifactId>
  25. <version>${ktor.version}</version>
  26. <scope>compile</scope>
  27. </dependency>
  28. </dependencies>
  29. </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 WebSocketSessioninterface for communication.

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

  1. val client = HttpClient {
  2. install(WebSockets)
  3. }

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

  1. client.ws(
  2. method = HttpMethod.Get,
  3. host = "127.0.0.1",
  4. port = 8080, path = "/route/path/to/ws"
  5. ) { // this: DefaultClientWebSocketSession
  6. // Send text frame.
  7. send("Hello, Text frame")
  8. // Send text frame.
  9. send(Frame.Text("Hello World"))
  10. // Send binary frame.
  11. send(Frame.Binary(...))
  12. // Receive frame.
  13. val frame = incoming.receive()
  14. when (frame) {
  15. is Frame.Text -> println(frame.readText())
  16. is Frame.Binary -> println(frame.readBytes())
  17. }
  18. }

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