在我的团队中,我们使用 WebSocketSubject 实现了 websocket。 根据它的文档,如果我只是触发它的下一个方法,它会向服务器发送一条消息。
我对 rxjs 还比较陌生,请跟我一起裸露:)。
这是我的代码:
// This provider service method simply returns websocket('websocketurl')
public connect() {
this.providerSvc
.webSocket()
.pipe(
switchMap((webSocket$?: WebSocketSubject<any>) => {
this.webSocket$ = webSocket$;
console.debug('Connected to WebSocket!');
this.connectionStateSource$.next(WebSocketConnectionState.CONNECTED);
this.isReconnecting.next(false);
console.debug('Starting heartbeat');
this.heartbeat();
return webSocket$.pipe(retry(15, 5000));
}),
takeUntil(this.imminentDestruction$),
)
.subscribe({
next: (message) => this.onMessageReceived(message),
error: (error) => this.onError(error),
complete: () => this.onClosed(),
});
});
}
private heartbeat() {
this.webSocket$.pipe(
map((message) => {
console.log(message, 'un mensaje!');
}),
timeoutWith(20000, throwError(() => new CustomWebsocketTimeout('slow'))),
timeoutWith(30000, throwError(() => new CustomWebsocketTimeout('lost'))),
catchError((error) => {
if (['slow', 'lost'].includes(error.type)) {
this.connectionStatus.next(error.type);
if(error.type === 'lost') this.refresh();
}
return error;
}),
);
interval(30000).pipe(
takeUntil(this.imminentDestruction$),
).subscribe(() => {
const timestamp = moment().unix();
// This is being fired every 30 seconds
// but can't see anything logged on chrome devtools
// I'm checking the websocket connection btw
this.webSocket$.next({message: 'ping_' +timestamp});
}, (error) => this.onError(error));
}
由于服务器不是 100% 可靠,我们团队决定实施一次心跳,以确保每隔 30' 套接字仍然处于活动状态,否则,触发重新连接流。
事实是,(如上面的评论中所述)当我尝试使用 next 发送消息时,它只是不发送。
我错过了什么?
我的错,正在查看错误的套接字连接。 对不起大家:/