RSocket WebSocket Client for Browsers

0.0.29-alpha.0 · active · verified Tue Apr 21

rsocket-websocket-client is a JavaScript library providing a WebSocket-based RSocket client implementation primarily designed for browser environments. It is part of the broader `rsocket-js` monorepo, which aims to provide a comprehensive JavaScript implementation of the RSocket protocol. As of its current version `0.0.29-alpha.0`, it is in an active alpha development phase, indicating that it is subject to rapid changes and not yet stable for production use. RSocket is a binary protocol for application-layer communication, enabling reactive streams with models like request/response, request/stream, fire-and-forget, and channel. This client focuses specifically on the WebSocket transport, making it suitable for web applications. Its key differentiator is its adherence to the RSocket specification, offering efficient, multiplexed, and reactive communication patterns over WebSockets, in contrast to traditional REST or simpler WebSocket protocols. The release cadence is currently irregular due to its alpha status, with updates reflecting progress on the overall RSocket.js implementation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting an RSocket client via WebSocket, performing a Request-Response interaction, and subscribing to a Request-Stream, including proper connection setup and teardown for a browser environment.

import { RSocketClient, BufferEncoders, RSocketConnection, Payload } from 'rsocket-core';
import { RSocketWebSocketClient } from 'rsocket-websocket-client';
import { Flowable } from 'rsocket-flowable';

// For browser environments, Buffer might not be globally available.
// Use TextEncoder/TextDecoder for explicit Uint8Array handling, or rely on build tool polyfills.
// This example uses Buffer.from for simplicity, which works well in Node.js or with polyfills.

async function connectAndInteract() {
  const client = new RSocketClient({
    serializers: BufferEncoders,
    setup: {
      keepAlive: 60000, // Milliseconds
      lifetime: 180000, // Milliseconds
      dataMimeType: 'application/json',
      metadataMimeType: 'message/x.rsocket.routing.v0', // Or 'message/x.rsocket.composite-metadata.v0'
    },
    transport: new RSocketWebSocketClient({
      url: 'ws://localhost:7000/rsocket', // Replace with your RSocket server's WebSocket URL
      // For browser environments, explicitly provide a WebSocket constructor:
      wsCreator: (url) => new WebSocket(url),
    }),
  });

  let rsocket: RSocketConnection | null = null;
  try {
    rsocket = await client.connect();
    console.log('RSocket client connected successfully.');

    // --- Request-Response interaction ---
    console.log('\nSending Request-Response...');
    const rrPayload: Payload = {
      data: Buffer.from(JSON.stringify({ request: 'greeting' })),
      metadata: Buffer.from('hello.world'), // Simple routing key
    };
    const rrResult = await Flowable.from<Payload>(rsocket.requestResponse(rrPayload)).first().toPromise();
    console.log('Request-Response received:', rrResult.data?.toString());

    // --- Request-Stream interaction ---
    console.log('\nSending Request-Stream...');
    const rsPayload: Payload = {
      data: Buffer.from(JSON.stringify({ count: 3 })),
      metadata: Buffer.from('stream.data'), // Simple routing key
    };
    rsocket.requestStream(rsPayload).subscribe({
      onComplete: () => console.log('Request-Stream completed.'),
      onError: (error) => console.error('Request-Stream error:', error),
      onNext: (payload) => console.log('Request-Stream data:', payload.data?.toString()),
      onSubscribe: (subscription) => subscription.request(Infinity), // Request all available items
    });

    // Keep the connection open for a few seconds to receive stream data
    await new Promise(resolve => setTimeout(resolve, 5000));

  } catch (error) {
    console.error('Failed to connect or interact with RSocket server:', error);
  } finally {
    if (rsocket) {
      client.close();
      console.log('RSocket client disconnected.');
    }
  }
}

connectAndInteract();

view raw JSON →