Getting started

Installation

In order to work with WebSockets module you need to install WebSocket module:

$ npm i @marblejs/websockets

or if you are a hipster:

$ yarn add @marblejs/websockets

Bootstrapping

Like httpListener the WebSocket module defines a similar way for bootstrapping. The webSocketListener includes definitions of all middlewares and WebSocket effects.

webSocket.listener.ts
const effects = [
effect1$,
effect2$,
// ...
];
const middlewares = [
middleware1$,
middleware2$,
// ...
];
export default webSocketListener({ effects, middlewares });

To connect the previously configured WebSocket listener, you have to create a context token first.

tokens.ts
import { createContextToken } from '@marblejs/core';
import { MarbleWebSocketServer } from '@marblejs/websockets';
export const WebSocketServerToken = createContextToken<MarbleWebSocketServer>();

You can learn more about Marble.js Context mechanism here.

Then all you have to do is to register the defined module inside createServer dependencies.

index.ts
import { bindTo createServer } from '@marblejs/core';
import { WebSocketServerToken } from './tokens.ts';
import httpListener from './http.listner.ts';
import webSocketListener from './webSocket.listner.ts';
const server = createServer({
// ...
httpListener,
dependencies: [
bindTo(WebSocketServerToken)(webSocketListener({ port: 8080 }).run),
],
// ...
});
server.run();

You can create and run a WebSocket server by providing the port value in webSocketListener config object. You can also upgrade the currently running http server by providing noServer: true in config object or by ommiting it.

If you are curious about other ways of bootstrapping the WebSocket server, reach out the Server events chapter.