WebSocketSession PRO

Requires Scripting 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:

Name Type Description
text string The text content to send.

Example:

1server.registerWebsocket("/chat", {
2  onConnected: (session) => {
3    session.writeText("Welcome to the chat room!")
4  },
5  handleText: (session, text) => {
6    console.log("Client says:", text)
7    session.writeText("You said: " + text)
8  }
9})

writeData(data: Data): void

Sends a binary message to the connected client.

Parameters:

Name Type Description
data Data The binary data to send.

Example:

1server.registerWebsocket("/binary", {
2  onConnected: (session) => {
3    const msg = Data.fromRawString("Binary hello", "utf-8")
4    session.writeData(msg)
5  }
6})

close(): void

Closes the WebSocket session. After calling this method, the connection is terminated and no further messages will be received or sent.

Example:

1server.registerWebsocket("/ws", {
2  handleText: (session, text) => {
3    if (text === "bye") {
4      session.writeText("Goodbye!")
5      session.close()
6    }
7  }
8})

Integration with HttpServer.registerWebsocket()

WebSocketSession instances are passed into the event handlers defined in registerWebsocket().

Example

1const connectedSessions: WebSocketSession[] = []
2
3server.registerWebsocket("/ws", {
4  onConnected: (session) => {
5    connectedSessions.push(session)
6    console.log("Client connected")
7    session.writeText("Connection established!")
8  },
9  handleText: (session, text) => {
10    console.log("Received:", text)
11    // Broadcast message to all clients
12    for (const s of connectedSessions) {
13      s.writeText("Broadcast: " + text)
14    }
15  },
16  handleBinary: (session, data) => {
17    console.log("Received binary data:", data.length)
18  },
19  onDisconnected: (session) => {
20    const index = connectedSessions.indexOf(session)
21    if (index !== -1) connectedSessions.splice(index, 1)
22    console.log("Client disconnected")
23  }
24})

Common WebSocket Event Handlers

These handlers are defined in HttpServer.registerWebsocket() and receive WebSocketSession objects.

Handler Trigger Parameters Description
onConnected When a new connection is established (session: WebSocketSession) Called once when a client connects.
onDisconnected When the client disconnects (session: WebSocketSession) Called when the connection is closed.
onPong When a ping/pong frame is received (session: WebSocketSession) Used for heartbeat or connection health checks.
handleText When a text message is received (session: WebSocketSession, text: string) Handles text-based messages.
handleBinary When a binary message is received (session: WebSocketSession, data: Data) Handles binary data messages.

Example: Simple Real-Time Chat Server

1const sessions: WebSocketSession[] = []
2
3server.registerWebsocket("/chat", {
4  onConnected: (session) => {
5    sessions.push(session)
6    session.writeText("Welcome! There are " + sessions.length + " users online.")
7  },
8  handleText: (session, text) => {
9    for (const s of sessions) {
10      s.writeText(text) // Broadcast message to all connected clients
11    }
12  },
13  onDisconnected: (session) => {
14    const index = sessions.indexOf(session)
15    if (index !== -1) sessions.splice(index, 1)
16  }
17})

Client example (JavaScript):

1const ws = new WebSocket("ws://localhost:8080/chat")
2ws.onmessage = e => console.log("Server:", e.data)
3ws.send("Hello everyone!")

Type Definition

1class WebSocketSession {
2  writeText(text: string): void
3  writeData(data: Data): void
4  close(): void
5}

Summary

Method Description Typical Use Case
writeText() Sends a text message to the client Chat, notifications, logs
writeData() Sends binary data to the client File transfer, streaming, IoT data
close() Closes the WebSocket connection Graceful shutdown or cleanup