Kest

Search

Search the documentation

WebSockets

Gateways

Two-way, real-time messaging between a browser (or app) and your server.

With HTTP the client asks and the server answers, once. A WebSocket is a connection that stays open, and either side can send a message at any time. Use it for chat, live dashboards, collaborative editing, games, notifications. In Kest the class that handles WebSocket connections is a gateway.

A gateway is declared like a controller: @WebSocketGateway("/chat") on a class, no @Injectable, listed in the module's controllers.

@Module(controllers = [ChatGateway::class]) class ChatModule
data class ChatMessage(val room: String, val text: String)
 
@WebSocketGateway("/chat")
class ChatGateway(private val server: WsServer) : OnGatewayConnection, OnGatewayDisconnect {
 
    override fun handleConnection(client: WsClient) {                        // a client connected
        val name = client.request.query["name"]?.firstOrNull()
        if (name == null) { client.close(4401, "name required"); return }    // refuse the connection
        client.attributes["name"] = name                                       // per-connection state lives here
    }
    override fun handleDisconnect(client: WsClient) { }                       // a client left
 
    @SubscribeMessage("join")                                                 // a message {"event":"join","data":"lobby"}
    fun join(client: WsClient, room: String) { client.join(room); server.to(room).emit("joined", client.attributes["name"]) }
 
    @SubscribeMessage("say")
    fun say(client: WsClient, msg: ChatMessage) =
        server.to(msg.room).emit("message", mapOf("from" to client.attributes["name"], "text" to msg.text), except = client)
 
    @SubscribeMessage("echo") fun echo(text: String): String = text.uppercase()       // the return value is the acknowledgement
}
 
app.http(NettyHttpAdapter(8080)) { useWebSockets() }

The protocol

Messages are JSON {"event": "...", "data": ...}, both ways. A browser client:

const ws = new WebSocket("ws://localhost:8080/chat?name=ann");
ws.onopen = () => ws.send(JSON.stringify({ event: "join", data: "lobby" }));
ws.onmessage = (m) => { const { event, data } = JSON.parse(m.data); console.log(event, data); };
ws.send(JSON.stringify({ event: "say", data: { room: "lobby", text: "hi" } }));

A handler's parameters: a WsClient parameter is the connection; the first other parameter is the message's data, decoded (and validated) into its type. A non-null return value is sent back to that client under the same event name (an acknowledgement). Bad input gets an error message (not JSON, missing event, unknown event); an HttpException thrown by a handler (or a guard or pipe) is sent as an exception message { "status": 403, "message": "..." }; anything unexpected is logged, reported to error monitoring and sent as { "status": 500, "message": "Internal server error" }.

Rooms and reaching clients

client.join(room) / client.leave(room)put a connection in a room or take it out
server.to(room).emit(event, data, except = client)everyone in the room (optionally not the sender)
server.broadcast(event, data)every connection
client.send(event, data)one connection
server.clients()the open connections
client.attributesper-connection values (user name, id)
client.requestthe handshake: query string, headers, cookies
Loading diagram…

Concurrency

Each connection's messages are handled in order, on a virtual thread; different connections run in parallel. A gateway is shared by all connections, so keep per-connection state in client.attributes, not in fields.

Signing in

A browser's WebSocket cannot set headers, so authenticate with a cookie (same site), or a short-lived token in the URL (?token=...), and check it in handleConnection (then client.close(4401, ...) to refuse) or in a guard.

Several instances

Rooms live in one process. Behind a load balancer use the Redis adapter so a message sent on one instance reaches clients on all of them.

Testing

Connect with the JDK's HttpClient.newWebSocketBuilder() against a test server on port 0, send JSON, and read the replies from a queue (the repository's WebSocket tests do exactly this).

Read more