如何在没有主题的情况下将WS Server正确转向RXJS Api

在Node.js中将着名的ws模块转换为响应式api的正确方法是什么? 我明白,科目可以帮助桥接非react native事件和react native事件,但是他们的问题在于,处理其相关对象的时间要困难得多。

var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8080 }); var Rx = require('rx'); var connectionMessageSubject = new Rx.Subject(); wss.on('connection', function connection(client) { ws.on('message', function incoming(message) { connectionMessageSubject.onNext({ client: client, message: message }); }); }); 

我不能使用它们内置的fromEvent方法,因为它注册了许多不同的事件,当30个或更多的客户端连接时,NodeJS会发出警告。

例如…

 var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({port:8080}); var connectionMessageObservable; //this uses a tremendous amount of memory and throws warnings that the event emitter has a maximum of 30 listeners wss.on('connection', function connection(client){ connnectionMessageObservable = Rx.Observable.fromEvent(client, 'message'); }); 

       

网上收集的解决方案 "如何在没有主题的情况下将WS Server正确转向RXJS Api"

以下代码模拟subject行为。

 var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({port:8080}); var connectionMessage$ = new Rx.Observable(function (observer) { wss.on('connection', function connection(client){ client.on('message', function (message){ observer.next({ client: client, message: message, }) }); }); }); connectionMessage$.subscribe(function (cm) { // cm.client for client // cm.message for message });