Skip to main content

Connections and rooms

Inject the current connection into a handler with @WsConnection(). The WebSocketConnection interface provides a transport-independent API for sending events and managing rooms:

import { WebSocket, WebSocketEvent, WsConnection, WsData } from '@axisparkjs/websocket';
import type { WebSocketConnection } from '@axisparkjs/websocket';

@WebSocket('/chat')
export class ChatWebSocket {
@WebSocketEvent('join')
joinRoom(
@WsConnection() connection: WebSocketConnection,
@WsData() data: { room: string }
) {
connection.join(data.room);
connection.emit('joined', { room: data.room });
}

@WebSocketEvent('leave')
leaveRoom(
@WsConnection() connection: WebSocketConnection,
@WsData() data: { room: string }
) {
connection.leave(data.room);
}
}

The connection interface exposes:

Property or methodDescription
idUnique connection identifier.
namespaceNamespace for this connection, when supported by the adapter.
roomsRooms the connection currently belongs to, when supported by the adapter.
connectedWhether the underlying connection is still open.
emit(event, data?)Send an event to this connection.
join(room) / leave(room)Join or leave a room, when supported by the adapter.
broadcast(room, event, data?)Send an event to a room according to the adapter's broadcast semantics.
close(code?, reason?)Close the connection.

The Socket.IO adapter maps these methods to the corresponding Socket.IO socket operations. In particular, its broadcast sends to the room while excluding the current socket.