SockJS facilitates real-time, bidirectional communication by providing a WebSocket-like client API. It gracefully falls back to alternative transports (e.g., HTTP streaming) when WebSocket is unavailable.
Creating a Client Connection
Establish a connection by creating a SockJS instance, specifying the server endpoint.
const dataStream = new SockJS('/api/streaming-endpoint');
Connection Lifecycle Handlers
Manage connection states by asisgning handlers to lifecycle events.
Handling an Established Connection
The onopen event fires when the conenction is ready.
dataStream.onopen = function handleOpen() {
console.log('Connection to server is active.');
};
Processing Incoming Messages
The onmessage event delivers data from the server.
dataStream.onmessage = function handleMessage(e) {
console.log(`Server payload: ${e.data}`);
// Application logic for processing data
};
Handling Connection Termination
The onclose event signals the end of the connection.
dataStream.onclose = function handleClose(e) {
console.log(`Connection terminated. Code: ${e.code}, Reason: ${e.reason}`);
};
Core Interaction Methods
Transmitting Data
Use the send() method to dispatch messages to the server.
dataStream.send(JSON.stringify({ action: 'update', payload: data }));
Initiating Disconnection Close the connection programmatically with an optional code and reason.
dataStream.close(3001, 'Client initiated shutdown');
Querying Connection State
The readyState property reflects the current phase of the connection.
function verifyConnectionStatus(stream) {
if (stream.readyState === SockJS.OPEN) {
console.log('Channel is open for communication.');
return true;
}
return false;
}
Managing Reconnection
While SockJS does not have a built-in reconnect() method, a connection can be re-established by creating a new instance, often within a close handler.
let connection;
function establishConnection() {
connection = new SockJS('/api/streaming-endpoint');
// ... assign event handlers
connection.onclose = function(e) {
console.log('Attempting to reconnect...');
setTimeout(establishConnection, 2000); // Re-attempt after a delay
};
}
establishConnection();