node-jet
Version:
Jet Realtime Message Bus for the Web. Daemon and Peer implementation.
58 lines (57 loc) • 1.98 kB
JavaScript
import JsonRPC from './index.js';
import { EventEmitter } from '../1_socket/index.js';
import { TCPServer } from '../1_socket/tcpserver.js';
import { WebsocketServer } from '../1_socket/wsserver.js';
/**
* JSONRPCServer instance
*/
export class JsonRPCServer extends EventEmitter {
config;
tcpServer;
wsServer;
connections = {};
log;
batches;
constructor(log, config, batches = false) {
super();
this.config = config;
this.batches = batches;
this.log = log;
}
listen = () => {
if (this.config.tcpPort) {
this.tcpServer = new TCPServer(this.config);
this.tcpServer.addListener('connection', (sock) => {
const jsonRpc = new JsonRPC(this.log, { batches: this.batches }, sock);
this.connections[sock.id] = jsonRpc;
this.emit('connection', jsonRpc);
});
this.tcpServer.addListener('disconnect', (sock) => {
this.emit('disconnect', this.connections[sock.id]);
delete this.connections[sock.id];
});
this.tcpServer.listen();
}
if (this.config.wsPort || this.config.server) {
this.wsServer = new WebsocketServer(this.config);
this.wsServer.addListener('connection', (sock) => {
const jsonRpc = new JsonRPC(this.log, { batches: this.batches }, sock);
this.connections[sock.id] = jsonRpc;
this.emit('connection', jsonRpc);
});
this.wsServer.addListener('disconnect', (sock) => {
this.emit('disconnect', this.connections[sock.id]);
delete this.connections[sock.id];
});
this.wsServer.listen();
}
};
close = () => {
if (this.tcpServer) {
this.tcpServer.close();
}
if (this.wsServer) {
this.wsServer.close();
}
};
}