The bootstrap comes preloaded with sockets! This feature is turned off by default but can be turned on via the application config.
The server uses express-ws
. By default, all socket messages are stringified JSON objects containing an instruction and data.
To enable sockets use this config block:
{
"websocket": {
"enabled": true
}
}
To catch updates from clients use the following code:
const NextBootstrap = require('@dpdk/bootstrap');
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.websocket.update = (ws, data) => {
// Custom code here
console.log('Socket Data: ', data);
};
bootstrap.init();
To send updates to all sockets the bootstrap exposes the following function:
const NextBootstrap = require('@dpdk/bootstrap');
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.init();
// Send update to all sockets
bootstrap.websocket.send("hello", {
some: "data"
});
To catch socket connects use the following code:
const NextBootstrap = require('@dpdk/bootstrap');
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.websocket.connect = (ws) => {
// Custom code here
};
bootstrap.init();
To catch socket disconnects use the following code:
const NextBootstrap = require('@dpdk/bootstrap');
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.websocket.disconnect = (ws) => {
// Custom code here
};
bootstrap.init();
Additional Express WS Documentation: https://www.npmjs.com/package/express-ws
Additional WebSocket Documentation: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
Last modified | Friday, April 30, 2021, 12:00:21 PM UTC |
Last author | Colin van Eenige |
Commit ID | 4c7a701 |