WebSocket Connection
Catalyst Data Streams enables clients to receive real-time data by establishing a WebSocket connection to a channel. The client listens for published messages and processes them as they are received.
To subscribe to a channel, you must first generate a token pair, then create a WebSocket client with the token credentials, and finally set event handlers to handle incoming messages.
The datastreams reference used in the code below is the component instance created earlier.
Establish WebSocket Connection
You must initially generate a token pair using the getTokenPair() method as shown below. Then, create a WebSocket client by passing the token credentials to the DataStreamsWebSocket constructor.
//Generate token pair
const response = await datastreams.getTokenPair(CRICKET_CHANNEL_ID, {
userId: "userId"
});
//Create WebSocket client
const socket = new DataStreamsWebSocket({
url: response.url,
zuid: response[“wss-id”],
key: response.key,
enableLogging: true
});
//Handling WebSocket events
socket.on(“open”, () => {
console.log(“WebSocket connection opened”);
socket.subscribe(“0”); //Subscribe to live data
});
socket.on(“message”, (data) => {
console.log(“WebSocket message received:”, data);
socket.sendAck(); //Acknowledge to receive next message
});
socket.on(“error”, (error) => {
console.error(“WebSocket error:”, error);
});
socket.on(“close”, () => {
console.log(“WebSocket connection closed”);
});
WebSocket Client Methods
The DataStreamsWebSocket client provides the following methods to manage the WebSocket connection and subscription.
| Method | Description |
|---|---|
| subscribe() | Subscribes to the channel with the specified subscribe type: live, earliest, resume, or a specific streaming ID. |
| unsubscribe() | Unsubscribes from the channel. |
| sendAck() | Sends an acknowledgement to receive the next streaming data. |
| close() | Closes the WebSocket connection. |
| isConnected() | Checks whether the connection is currently open. |
| getConnectionState() | Returns the current connection state: connected, connecting, closing, or closed. |
| getSessionInfo() | Returns the session ID and user ID of the current session. |
Last Updated 2026-10-05 20:43:57 +0530 IST
Yes
No
Send your feedback to us