TinyBase logoTinyBase

createWsServer

The createWsServer function creates a WsServer that facilitates synchronization between clients that are using WsSynchronizer instances.

createWsServer(webSocketServer: WebSocketServer): WsServer
TypeDescription
webSocketServerWebSocketServer

A WebSocketServer object from your server environment.

returnsWsServer

A reference to the new WsServer object.

This should be run in a server environment, and you must pass in a configured WebSocketServer object in order to create it.

Examples

This example creates a WsServer and then destroys it again.

import {WebSocketServer} from 'ws';
import {createWsServer} from 'tinybase/synchronizers/synchronizer-ws-server';

const server = createWsServer(new WebSocketServer({port: 8047}));
server.destroy();

This example creates a WsServer with a custom listener that displays information about the address of the client that connects to it.

import {WebSocket, WebSocketServer} from 'ws';
import {createMergeableStore} from 'tinybase';
import {createWsServer} from 'tinybase/synchronizers/synchronizer-ws-server';
import {createWsSynchronizer} from 'tinybase/synchronizers/synchronizer-ws-client';

// On the server:
const webSocketServer = new WebSocketServer({port: 8047});
webSocketServer.on('connection', (_, request) => {
  console.log('Client address: ' + request.socket.remoteAddress);
});
const server = createWsServer(webSocketServer);

// On a client:
const synchronizer = await createWsSynchronizer(
  createMergeableStore(),
  new WebSocket('ws://localhost:8047'),
);
// -> 'Client address: ::1'

synchronizer.destroy();
server.destroy();

Since

v5.0.0