123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import { Injectable } from "@angular/core";
- import { Subject, Observable, from } from "rxjs";
- import * as Atmosphere from "atmosphere.js";
- @Injectable({
- providedIn: "root",
- })
- export class WebsocketMainService {
- constructor() {}
- private lockReconnect = false;
- ws;
- private url = "";
- private urlParams;
- private isHandler = false;
- private subject;
-
- connectWs(url, data): Observable<any> {
- this.url = url;
- this.urlParams = data;
- this.subject = new Subject<any>();
- let request: any = {
- url,
- contentType: "application/json",
- shared: true,
- trackMessageLength: true,
- transport: "websocket",
- };
- request.onOpen = (response) => {
- console.log("ws连接成功" + new Date().toLocaleString());
- this.heartCheck.reset().start(this);
- this.ws.push(JSON.stringify(data));
- };
- request.onMessage = (response) => {
- this.heartCheck.reset().start(this);
- let message = response.responseBody;
- try {
-
- console.log("收到消息" + message);
- if (message !== "pong") {
- this.subject.next(JSON.parse(message));
- }
- } catch (e) {
- console.log("This doesn't look like a valid JSON: ", message);
- return;
- }
- };
- request.onClose = (response) => {
- console.log("ws连接关闭" + new Date().toLocaleString(),this.isHandler);
- this.heartCheck.reset();
- if (!this.isHandler) {
- this.reconnect(this.url, this.urlParams);
- }
- };
- request.onError = (response) => {
- console.log("ws连接错误",this.isHandler);
- this.heartCheck.reset();
- if (!this.isHandler) {
- this.reconnect(this.url, this.urlParams);
- }
- };
- this.ws = Atmosphere.subscribe(request);
- return this.subject.asObservable();
- }
-
- private reconnect(url, data) {
- if (this.lockReconnect) return;
- this.lockReconnect = true;
- setTimeout(() => {
-
- this.connectWs(url, data);
- this.lockReconnect = false;
- }, 15000);
- }
- private heartCheck = {
- timeout: 60000,
- timeoutObj: null,
- serverTimeoutObj: null,
- reset: function () {
- clearTimeout(this.timeoutObj);
- clearTimeout(this.serverTimeoutObj);
- return this;
- },
- start: function (_this) {
- this.timeoutObj = setTimeout(() => {
-
-
- _this.ws.push("ping");
- this.serverTimeoutObj = setTimeout(() => {
-
- _this.closeWs();
- }, this.timeout);
- }, this.timeout);
- },
- };
-
- closeWs(flag: boolean = false) {
- this.isHandler = flag;
- this.ws.close();
- }
- }
|