createWsServerSimple
The createWsServerSimple function creates a WsServerSimple that facilitates synchronization between clients that are using WsSynchronizer instances.
createWsServerSimple(webSocketServer: WebSocketServer): WsServerSimple| Type | Description | |
|---|---|---|
webSocketServer | WebSocketServer | A WebSocketServer object from your server environment. |
| returns | WsServerSimple | A reference to the new |
This should be run in a server environment, and you must pass in a configured WebSocketServer object in order to create it.
The core functionality is equivalent to the WsServer interface, but without the complications of listeners, persistence, or statistics. This makes it more suitable to be used as a reference implementation for other server environments.
Since v9.3, it also supports multiple channel-based WsSynchronizer instances sharing one WebSocket. Once a client WebSocket is accepted on a base path, it can subscribe to any valid channel beneath that path: WsServerSimple does not authenticate or authorize channel Ids. For untrusted clients, use a separate authenticated WebSocket for each authorized path unless access to all descendants is acceptable.
Example
This example creates a WsServerSimple that synchronizes two clients on a shared path.
import {createMergeableStore} from 'tinybase';
import {createWsSynchronizer} from 'tinybase/synchronizers/synchronizer-ws-client';
import {createWsServerSimple} from 'tinybase/synchronizers/synchronizer-ws-server-simple';
import {WebSocket, WebSocketServer} from 'ws';
// Server
const server = createWsServerSimple(new WebSocketServer({port: 8053}));
// Client 1
const clientStore1 = createMergeableStore();
clientStore1.setCell('pets', 'fido', 'species', 'dog');
const synchronizer1 = await createWsSynchronizer(
clientStore1,
new WebSocket('ws://localhost:8053/petShop'),
);
await synchronizer1.startSync();
// ...
// Client 2
const clientStore2 = createMergeableStore();
clientStore2.setCell('pets', 'felix', 'species', 'cat');
const synchronizer2 = await createWsSynchronizer(
clientStore2,
new WebSocket('ws://localhost:8053/petShop'),
);
await synchronizer2.startSync();
// ...
console.log(clientStore1.getTables());
// -> {pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}}
console.log(clientStore2.getTables());
// -> {pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}}
await synchronizer1.destroy();
await synchronizer2.destroy();
await server.destroy();
Since
v5.4.0