or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-api.mdevents.mdindex.mdtransports.md
tile.json

tessl/npm-sockjs-client

SockJS-client is a browser JavaScript library that provides a WebSocket-like object for establishing cross-browser, full-duplex communication channels between browsers and web servers.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sockjs-client@1.6.x

To install, run

npx @tessl/cli install tessl/npm-sockjs-client@1.6.0

index.mddocs/

SockJS-client

SockJS-client is a browser JavaScript library that provides a WebSocket-like object for establishing cross-browser, full-duplex communication channels between browsers and web servers. It creates low-latency, cross-domain communication by first attempting to use native WebSockets and falling back to various browser-specific transport protocols when WebSockets are unavailable.

The library maintains compatibility with the HTML5 WebSocket API while providing robust fallback mechanisms for older browsers and constrained network environments, including support for restrictive corporate proxies and cross-domain connections.

Package Information

  • Package Name: sockjs-client
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install sockjs-client
  • CDN: https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js

Core Imports

For browser environments using CDN:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

For Node.js or bundlers:

const SockJS = require('sockjs-client');

ES modules:

import SockJS from 'sockjs-client';

Basic Usage

// Create connection
const sock = new SockJS('https://mydomain.com/my_prefix');

// Set up event handlers
sock.onopen = function() {
    console.log('Connected');
    sock.send('Hello Server!');
};

sock.onmessage = function(e) {
    console.log('Received:', e.data);
};

sock.onclose = function() {
    console.log('Disconnected');
};

sock.onerror = function() {
    console.log('Connection error');
};

// Later: close connection
sock.close();

Architecture

SockJS-client is built around several key components:

  • SockJS Class: Main WebSocket-like interface providing connection management and message handling
  • Transport System: Automatic fallback mechanism supporting 11+ transport protocols from WebSocket to JSONP polling
  • Event System: DOM-compatible event handling with support for both handler properties and addEventListener
  • Browser Detection: Intelligent capability detection to select the most appropriate transport for each environment
  • Cross-Domain Support: Built-in support for cross-origin requests with cookie-based sticky sessions

Capabilities

Core Connection API

Primary SockJS class providing WebSocket-compatible interface for establishing and managing connections with automatic transport fallback.

/**
 * SockJS constructor - creates a new SockJS connection
 * @param {string} url - Connection URL (http/https), may contain query string
 * @param {string|string[]} [protocols] - Protocols (reserved parameter, typically not used)
 * @param {object} [options] - Configuration options
 */
function SockJS(url, protocols, options);

// Instance properties
SockJS.prototype.url;           // string - Connection URL
SockJS.prototype.readyState;    // number - Current connection state (0-3)
SockJS.prototype.extensions;    // string - Always empty string
SockJS.prototype.protocol;      // string - Always empty string  
SockJS.prototype.transport;     // string - Active transport name when connected

// Instance methods
SockJS.prototype.send(data);           // Send data (converts non-strings to strings)
SockJS.prototype.close(code, reason);  // Close connection with optional code and reason

// Static constants
SockJS.CONNECTING;  // 0 - Connection being established
SockJS.OPEN;        // 1 - Connection is open
SockJS.CLOSING;     // 2 - Connection is closing  
SockJS.CLOSED;      // 3 - Connection is closed

// Static property
SockJS.version;     // string - Library version

Core Connection API

Event System

DOM-compatible event handling system supporting both event handler properties and addEventListener/removeEventListener methods.

// Event handler properties
sock.onopen = function() { /* connection opened */ };
sock.onmessage = function(e) { /* message received: e.data */ };
sock.onclose = function(e) { /* connection closed: e.code, e.reason, e.wasClean */ };
sock.onerror = function() { /* connection error */ };

// EventTarget methods
sock.addEventListener(type, listener);    // Add event listener
sock.removeEventListener(type, listener); // Remove event listener
sock.dispatchEvent(event);               // Dispatch event

Event System

Transport Configuration

Flexible transport system with automatic fallback and manual configuration options for different network environments and browser capabilities.

// Constructor options for transport configuration
const options = {
  server: string,           // Server identifier (default: random 4-digit number)
  transports: string|Array, // Whitelist of allowed transports
  sessionId: number|function, // Session ID generation (default: 8 chars)
  timeout: number,          // Minimum timeout for transport connections
  transportOptions: object  // Transport-specific configuration
};

// Available transport names for whitelisting
const availableTransports = [
  'websocket',
  'xhr-streaming', 
  'xdr-streaming',
  'eventsource',
  'iframe-eventsource',
  'htmlfile',
  'iframe-htmlfile', 
  'xhr-polling',
  'xdr-polling',
  'iframe-xhr-polling',
  'jsonp-polling'
];

Transport Configuration

Types

// Options interface for SockJS constructor
interface SockJSOptions {
  server?: string;                    // Server identifier
  transports?: string | string[];     // Transport whitelist
  sessionId?: number | (() => string); // Session ID configuration
  timeout?: number;                   // Connection timeout
  transportOptions?: object;          // Transport-specific options
}

// Event objects
interface SockJSMessageEvent {
  type: 'message';
  data: any;    // Message payload
}

interface SockJSCloseEvent {
  type: 'close';
  code: number;      // Close code
  reason: string;    // Close reason
  wasClean: boolean; // Clean close flag
}

interface SockJSEvent {
  type: 'open' | 'error' | 'heartbeat';
}

Limitations and Considerations

  • Connection Limit: Only one SockJS connection per domain at a time due to browser connection limits
  • Data Types: All data is converted to strings before transmission
  • Cross-Origin: Requires server-side CORS support for cross-domain connections
  • Transport Cookies: Some transports (XDR) don't support cookies, affecting sticky sessions
  • Protocol Support: Only HTTP/HTTPS URLs are supported (no ws:// or wss://)

Browser Compatibility

SockJS-client provides comprehensive browser support through its transport fallback system:

  • Modern Browsers: WebSocket + XHR streaming/polling
  • IE 10+: WebSocket + XHR streaming/polling
  • IE 8-9: XDR streaming/polling or iframe-based transports
  • IE 6-7: JSONP polling only
  • Legacy Browsers: Graceful degradation to appropriate transport methods

The library automatically selects the best available transport based on browser capabilities and network environment.