Installation
The WebSocket Plugin provides the WebSocket event model for AxiSpark.js. It uses an adapter to provide the transport; this guide uses the Socket.IO adapter.
1. Install the packages
Install the WebSocket plugin and its Socket.IO adapter:
npm install @axisparkjs/websocket @axisparkjs/websocket-socketio
2. Register and configure the plugin
Pass the options factory to app.use. It selects the Socket.IO adapter and provides defaults: the /websocket path, a 5-second connection timeout, and port 3000.
import { AxiSparkFactory } from '@axisparkjs/core';
import { WebSocketPlugin } from '@axisparkjs/websocket';
import { WebSocketPluginOptionsFactory } from '@axisparkjs/websocket-socketio';
export const app = AxiSparkFactory.create({
...
});
app.use(WebSocketPlugin, WebSocketPluginOptionsFactory.create());
3. Use the HTTP Plugin server (optional)
By default, the Socket.IO adapter starts its own server on the configured port. To attach WebSockets to the HTTP server managed by the HTTP Plugin, register the HTTP Plugin and set useHttpPluginServer to true:
import { HttpPlugin, HttpPluginOptionsFactory } from '@axisparkjs/http';
app.use(HttpPlugin, HttpPluginOptionsFactory.create({ port: 3000 }));
app.use(WebSocketPlugin, WebSocketPluginOptionsFactory.create({
useHttpPluginServer: true
}));
When using the HTTP Plugin server, its port is used; the WebSocket port option is ignored. The HTTP Plugin is an optional dependency of the WebSocket Plugin, but it must be registered when useHttpPluginServer is enabled.
Configuration options
WebSocketPluginOptionsFactory.create() accepts these options:
| Option | Type | Default | Description |
|---|---|---|---|
path | string | '/websocket' | Socket.IO server path. |
port | number | 3000 | Port used when the plugin creates its own server. |
connectTimeout | number | 5000 | Milliseconds allowed for a client to connect to a namespace before it is disconnected. |
serveClient | boolean | true | Whether Socket.IO serves its client files. |
useHttpPluginServer | boolean | false | Whether to attach the adapter to the HTTP Plugin server. |
For an example of declaring namespaces and handling events, see WebSocket events.