Client WebSockets

note

Client WebSockets - 图1

This help topic is in development and will be updated in the future.

Ktor provides Websocket client support 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:

  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.