无论如何,如果我的应用程序与WebSocket断开连接,则无法重新连接它。我附上了示例代码,请向我建议如何重新连接WebSocket并再次在Web套接字服务器上初始化身份的想法。
我已经在本教程的帮助下完成了我的应用程序。
https://tutorialedge.net/typescript/angular/angular-websockets-tutorial/
除了我的应用程序要求外,我在应用程序中编写了相同的代码。
我所遵循的教程不具有在任何情况下(例如互联网中断)或由于某种原因重新启动WebSocket的功能,因为我正在使用SupervisorD运行WebSocket服务器,因此WebSocket服务器重新启动,如果WebSocket运行,它将自动重新启动服务器在任何情况下都会停止
我的应用程序正在生产中,并且许多客户正在使用它,因此我无法更改所有流程并在此应用程序中重新创建WebSocket的代码。
我正在添加我正在使用的所有代码
websocket.service.ts
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable()
export class WebsocketService {
connected: boolean = false;
initialized: boolean= false;
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
// console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
// here i am trying to reconnect my websocket
// setInterval (function () {
// if (ws.readyState !== 1) {
// ws = new WebSocket(url);
// this.initialized = false;
// }
// console.log(this.initialized);
// if (ws.readyState == 1 && this.initialized == false) {
// ws.send('{"type":"add",
"t":"14bfa6xxx", "from_numbers":
["xxxx","xxxxx"], "platform":"xxxx"}');
// this.initialized = true;
// }
// console.log(this.initialized);
// }, 4000);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
})
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
if (data['type'] == 'add') {
console.log("Connection Initialized");
}
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
Chat.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';
@Injectable()
export class ChatService {
public messages: Subject<Message>;
constructor(wsService: WebsocketService, private authService: AuthService) {
this.messages = <Subject<Message>>wsService
.connect(socket_url)
.map((response: MessageEvent): Message => {
const data = JSON.parse(response.data);
console.log(data);
return data;
});
}
}
最后,我已经在组件中使用了此功能来订阅消息。
constructor(private chatService: ChatService,) {
this.socketMessages();
}
socketMessages() {
this.chatService.messages.subscribe(msg => {
console.log(msg)
});
}