SockJS Client

1.6.1 · active · verified Sun Apr 19

SockJS-client is a browser JavaScript library (current stable version 1.6.1) that provides a WebSocket-like object, abstracting away underlying transport mechanisms. It aims to offer a coherent, cross-browser, full-duplex communication channel between the browser and a web server, even in environments without native WebSocket support or behind restrictive corporate proxies. The library first attempts to use native WebSockets, falling back to various browser-specific transports (like streaming or polling) if necessary. Releases are somewhat irregular but active, with recent updates focusing on security fixes and dependency updates. A key differentiator is its robust fallback mechanism, adhering closely to the HTML5 WebSocket API, and supporting cross-domain connections without requiring Flash. It explicitly requires a server counterpart, such as `sockjs-node`, for functionality.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to establish a connection with a SockJS server, send messages, and handle connection lifecycle events like opening, receiving messages, and closing. It also highlights the necessity of a server counterpart.

import SockJS from 'sockjs-client';

// Ensure a SockJS server is running, e.g., on http://localhost:8080/my_websocket
// For example, using sockjs-node:
// const sockjs = require('sockjs');
// const http = require('http');
// const server = http.createServer();
// const echo = sockjs.createServer();
// echo.on('connection', (conn) => {
//   conn.on('data', (message) => { conn.write(message); });
//   conn.on('close', () => { console.log('Client disconnected from server'); });
// });
// echo.installHandlers(server, { prefix: '/my_websocket' });
// server.listen(8080, '0.0.0.0', () => { console.log('SockJS server listening on 8080'); });

const socket = new SockJS('http://localhost:8080/my_websocket');

socket.onopen = () => {
  console.log('SockJS connection opened');
  socket.send('Hello from client!');
};

socket.onmessage = (event) => {
  console.log('Received message:', event.data);
  // Optionally close the connection after receiving a message
  // socket.close();
};

socket.onclose = (event) => {
  console.log('SockJS connection closed:', event.code, event.reason);
  if (!event.wasClean) {
    console.error('Connection abruptly disconnected.');
    // Implement re-connection logic here
  }
};

socket.onerror = (error) => {
  console.error('SockJS error:', error);
};

// Example: Send a message every 3 seconds
// setInterval(() => {
//   if (socket.readyState === SockJS.OPEN) {
//     socket.send('Ping!');
//   }
// }, 3000);

view raw JSON →