我使用rxjs中的WebSocketSubject为我的websocket连接创建了一个可观察对象。目前为止,服务器-客户端通信正常工作。现在的问题是:我无法区分客户端消息的来源。通过在主题上调用next()发送消息,所有客户端的订阅者都会收到这些消息。如何只向服务器发送消息?
实现主要源自这篇文章:https://medium.com/factory-mind/angular-websocket-node-31f421c753ff 我的代码:
实现主要源自这篇文章:https://medium.com/factory-mind/angular-websocket-node-31f421c753ff 我的代码:
socket$: WebSocketSubject<any>;
constructor() {
this.socket$ = WebSocketSubject.create(SOCKET_URL);
this.socket$.subscribe(
(message) => console.log('<-- ' + message),
(err) => console.error('Error on WebSocket:', err),
() => console.warn('Completed!')
);
}
send(message: SocketMessage) {
const tmp: any = {};
tmp.type = message.type;
tmp.payload = message.payload;
// This will be received by the server but also by client subscriptions = bad
this.socket$.next(JSON.stringify(tmp));
}