【发布时间】:2021-05-20 21:16:25
【问题描述】:
我正在我的平台中实现 WebSockets 连接。我在前端使用 Angular 10,在 SockJS Client 1.5.0 上使用 StompJS 2.3.3 来建立与后端的连接。
我创建了一个 WebSockets 服务来管理连接,它正在连接并正常工作。
这是我创建的服务:
export class WebSocketsService implements OnDestroy {
/**
* The authentication service to get the token from.
*/
private authenticationService: AuthenticationService;
private serverUrl = environment['ceNotificationsServer'];
private socket;
private state: BehaviorSubject<SocketClientState>;
public constructor(authenticationService: AuthenticationService) {
this.authenticationService = authenticationService;
const client_id = environment['ceNotificationsClientId'];
const token = this.authenticationService.getToken();
const url = this.serverUrl + '/websocket' + '?clientId=' + client_id + '&Authorization=' + token;
const ws = new SockJS(url);
this.socket = StompJS.over(ws);
this.socket.reconnect_delay = 5000;
this.socket.debug = () => {
};
this.state = new BehaviorSubject<SocketClientState>(SocketClientState.ATTEMPTING);
this.socket.connect({}, () => {
this.state.next(SocketClientState.CONNECTED);
console.log('Connection to the socket is open.');
});
}
/**
* Establish the connection to the websocket.
*/
connect(cfg: { reconnect: boolean } = {reconnect: false}): Observable<any> {
return new Observable(observer => {
this.state.pipe(
cfg.reconnect ? this.reconnect : o => o,
filter(state => state === SocketClientState.CONNECTED))
.subscribe(() => {
observer.next(this.socket);
});
});
}
message(queue: String): Observable<any> {
return this.connect({reconnect: true})
.pipe(switchMap(client => {
return new Observable<any>(observer => {
client.subscribe(queue, message => {
observer.next(JSON.parse(message.body));
});
});
}),
retryWhen((errors) => errors.pipe(delay(5))));
}
reconnect(observable: Observable<any>): Observable<any> {
return observable.pipe(
retryWhen(errors => errors.pipe(
tap(val => console.log('Trying to reconnect to the socket', val)),
delayWhen(_ => timer(5000))
))
);
}
/**
* Close the connection to the websocket.
*/
close() {
if (this.socket) {
this.socket.complete();
this.state.next(SocketClientState.CLOSED);
console.log('Connection to the socket is closed');
this.socket = null;
}
}
ngOnDestroy() {
this.close();
}
}
export enum SocketClientState {
ATTEMPTING, CONNECTED, CLOSED
}
在我的 Angular 组件中,我添加了这段代码来订阅 WebSockets 队列并获取一些通知来填充我的通知托盘:
const subscription1 = this.websocketsService.message('/messages')
.subscribe(outdatedProfiles => {
const notification: Notification = outdatedProfiles;
notification.message = 'notificationNotSyncedProviders';
this.notifications.addNotification(notification);
});
this.subscriptionsManager.add(subscription1);
我的问题是,当我失去连接时(如果 wifi 断开连接),它不会再次重新连接。它会捕获错误,但不会捕获连接关闭事件。
我试过this的方法:
public constructor(authenticationService: AuthenticationService) {
this.socket.connect({}, () => {...});
this.socket.onclose = function(event) {
console.log("WebSocket is closed now.");
this.connect({reconnect: true});
};
}
但它不起作用。我已阅读文档,但连接关闭时似乎无法找到重新连接问题的答案。有什么想法吗?
【问题讨论】:
-
看起来新版本的 StompJS 包含一个 rx 版本。我提到是因为看起来您的服务正在返回可观察状态。也许这会引起RxStomp 的兴趣。 “RxStomp 还尝试透明地处理连接失败。”
-
谢谢@BizzyBob 我会研究一下
标签: angular websocket stomp sockjs