WebSocketSession PRO
The WebSocketSession class represents an active WebSocket connection session.
It is created automatically when a client connects to a WebSocket endpoint registered via HttpServer.registerWebsocket() and enables bi-directional real-time communication between the server and the client.
Overview
Through a WebSocketSession, you can:
- Receive text or binary data from clients
- Send messages (text or binary) back to clients
- Handle connection and disconnection events
- Close the WebSocket connection gracefully
Each WebSocketSession instance corresponds to one client connection and can be managed individually or stored for broadcasting messages.
Use Cases
- Real-time chat or collaboration systems
- Live notifications or dashboard updates
- Device control or IoT message channels
- Local WebSocket servers communicating with other devices or web clients
Methods
writeText(text: string): void
Sends a text message to the connected client.
Parameters:
Example:
writeData(data: Data): void
Sends a binary message to the connected client.
Parameters:
Example:
close(): void
Closes the WebSocket session. After calling this method, the connection is terminated and no further messages will be received or sent.
Example:
Integration with HttpServer.registerWebsocket()
WebSocketSession instances are passed into the event handlers defined in registerWebsocket().
Example
Common WebSocket Event Handlers
These handlers are defined in HttpServer.registerWebsocket() and receive WebSocketSession objects.
Example: Simple Real-Time Chat Server
Client example (JavaScript):
