Ktor supports the WebSocket protocol and allows you to create applications that require real-time data transfer from and to the server. For example, WebSockets can be used to create a chat application.
The Ktor client allows you to handle a WebSocket session for exchanging messages with the server. To learn about WebSocket support in a Ktor server, see Server WebSockets.
To use WebSockets, you need to include the
ktor-client-websockets artifact in the build script:
To install the
WebSockets plugin, pass it to the
install function inside a client configuration block:
Optionally, you can configure the plugin inside the
install block by passing the required options using WebSockets.Config.
Handle a WebSockets session
To handle a client WebSocket session, call the webSocket function:
webSocket block, you need to handle a WebSocket session, which is represented by the DefaultClientWebSocketSession class. Session configuration might look as follows:
sendfunction to send text content to the server.
outgoingproperties to access the channels for receiving and sending WebSocket frames. A frame is represented by the Frame class.
When handing a session, you can check a frame type, for example:
Frame.Textis a text frame. For this frame type, you can read its content using
Frame.Binaryis a binary frame. For this type, you can read its content using
Frame.Closeis a closing frame. You can call
Frame.Close.readReason()to get a close reason for the current session.
closefunction to send a close frame with the specified reason.
The example below shows how to send a message to the
echo WebSocket endpoint and how to receive a response:
You can find the full example here: client-websockets.