generator-host
v1.0.1
Published
`generator-host` is a JavaScript library that allows you to create a multi-port WebSocket server. It supports creating WebSocket servers on multiple ports and handles incoming client requests through customizable decorator functions. You can easily add
Readme
GeneratorHost
generator-host is a JavaScript library that allows you to create a
multi-port WebSocket server. It supports creating WebSocket servers on
multiple ports and handles incoming client requests through customizable
decorator functions. You can easily add WebSocket servers, process data,
and customize the behavior of connections on a per-port basis.
Installation
npm i generator-hostUsage
Initializing GeneratorHost
First, you need to initialize a GeneratorHost object and
provide the list of ports on which you want the WebSocket server to listen.
import {GeneratorHost} from "generator-host";
// Initialize GeneratorHost with ports 7070 and 3030
// Default host ['8080']
const HostSocket = new GeneratorHost({ host: ["7070", "3030"] });
// Initialize servers and WebSocket
await HostSocket.init();
Customizing decorators for each port
You can use the portDecorator method to specify how to handle client messages for
each port separately. The decorator function will be called whenever the server receives a message from the client
HostSocket.portDecorator("7070", (clientMessage) => {
// Process client data and return the result
const convertedMessage = clientMessage + " editor";
return convertedMessage;
});Customizing decorators for each port
After initialization, you can check the list of ports that your WebSocket server is listening on
console.log(HostSocket.allport);Full Example
import {GeneratorHost} from "generator-host";
// Initialize with ports 7070 and 3030
const HostSocket = new GeneratorHost({ host: ["7070", "3030"] });
// Initialize WebSocket servers
await HostSocket.init();
// Customize decorator for port 7070
HostSocket.portDecorator("7070", (clientMessage) => {
return clientMessage + " - processed on 7070";
});
// Customize decorator for port 3030
HostSocket.portDecorator("3030", (clientMessage) => {
return clientMessage + " - processed on 3030";
});
// Check active ports
console.log(HostSocket.allport);