SocketCluster Client

20.0.1 · active · verified Sun Apr 19

SocketCluster Client (socketcluster-client) is the JavaScript client library for connecting to SocketCluster servers, enabling high-performance, real-time, bi-directional communication over WebSockets. It provides abstractions for pub/sub (channels), remote procedure calls (RPC), and efficient data streaming. The library is currently at version 20.0.1, indicating an active development cycle with frequent major releases that often introduce breaking changes. Key differentiators include its focus on scalability, built-in support for backpressure handling, and a clear API for consuming events and data streams using async iterators, making it suitable for demanding real-time applications like chat, gaming, and financial dashboards. It is designed to work seamlessly with `socketcluster-server`.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a SocketCluster server, transmitting data, invoking an RPC, subscribing to a channel, publishing to it, and consuming messages using async iterators.

import { create } from 'socketcluster-client';

const socket = create({
  hostname: 'localhost',
  port: 8000,
  autoConnect: true,
  autoReconnectOptions: {
    initialDelay: 1000,
    randomness: 500,
    multiplier: 1.2,
    maxDelay: 10000
  }
});

(async () => {
  try {
    await socket.listener('connect').once();
    console.log('Socket connected successfully to server.');

    // Transmit data to the server without expecting a response
    socket.transmit('chatMessage', { user: 'developer', text: 'Hello SocketCluster!' });

    // Invoke a remote procedure call (RPC) and await a response
    const serverTime = await socket.invoke('getServerTime');
    console.log('Server time received:', serverTime);

    // Subscribe to a channel and consume messages
    const myChannel = socket.subscribe('myPublicChannel');
    await myChannel.listener('subscribe').once();
    console.log('Successfully subscribed to channel: myPublicChannel');

    // Publish a message to the channel
    await myChannel.invokePublish('This is a message from the client.');
    console.log('Published message to channel.');

    // Consume messages from the channel using an async iterator
    for await (const data of myChannel) {
      console.log('Received channel message:', data);
      // For demonstration, process one message then unsubscribe
      break;
    }
    myChannel.unsubscribe();
    console.log('Unsubscribed from channel.');

  } catch (error) {
    console.error('Socket error or connection failed:', error);
  }

  // Disconnect the socket after a short delay
  setTimeout(() => {
    socket.disconnect();
    console.log('Socket disconnected.');
  }, 5000);
})();

view raw JSON →