WebSocket is a protocol which provides a full-duplex communication session between the user's browser and a server over a single TCP connection. It is particularly useful for creating applications that require real-time data transfer from and to the server. For example, WebSockets can be used to create a chat application.
Ktor supports the WebSocket protocol both on the server-, and the client-side.
Ktor allows you to:
Configure basic WebSocket settings, such as frame size, a ping period, and so on.
Handle a WebSocket session for exchanging messages between the server and client.
WebSockets, you need to include the
ktor-server-websockets artifact in the build script:
... inside the
... inside the explicitly defined
module, which is an extension function of the
Optionally, you can configure the plugin inside the
install block by passing WebSocketOptions:
pingPeriodproperty to specify the duration between pings.
timeoutproperty to set a timeout after which the connection to be closed.
maxFrameSizeproperty to set a maximum Frame that could be received or sent.
maskingproperty to specify whether masking is enabled.
contentConverterproperty to set a converter for serialization/deserialization.
Handle WebSockets sessions
Once you have installed and configured the
WebSockets plugin, you can define an endpoint to handle a Websocket session. To define a WebSocket endpoint on a server, call the
webSocket function inside the routing block:
In this example, the server accepts WebSocket requests to
ws://localhost:8080/echo when a default configuration is used.
webSocket block, you define the handler for the WebSocket session, which is represented by the DefaultWebSocketServerSession class. The following functions and properties are available within the block:
sendfunction to send text content to the client.
outgoingproperties to access the channels for receiving and sending WebSocket frames. A frame is represented by the
closefunction to send a close frame with the specified reason.
When handling 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
Below, we'll take a look at the examples of using this API.
Example: Handle a single session
The example below shows how to create the
echo WebSocket endpoint to handle a session with one client:
For the full example, see server-websockets.
Example: Handle multiple sessions
To handle multiple WebSocket sessions (for example, in a chat application), you need to store each session on a server. To do this, you define a connection with a unique name and associate it with a specified session. A sample
Connection class below shows how to do this:
Then, you can create a new connection inside the
webSocket handler when a new client connects to the WebSocket endpoint:
For the full example, see tutorial-websockets-server.
The WebSocket API and Ktor
The standard events from the WebSocket API map to Ktor in the following way:
onConnecthappens at the start of the block.
onMessagehappens after successfully reading a message (for example, with
incoming.receive()) or using suspended iteration with
for(frame in incoming).
onClosehappens when the
incomingchannel is closed. That would complete the suspended iteration, or throw a
ClosedReceiveChannelExceptionwhen trying to receive a message.
onErroris equivalent to other exceptions.
closeReason property is set.
In the following example, the infinite loop will only be exited when an exception has risen (either a
ClosedReceiveChannelException or another exception):