Angular WebSocket

宋安晏
2023-12-01
/**
 * websocket服务
 */
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import {Subject} from 'rxjs';
import {BaseService} from "./base.service";

@Injectable()
export class  WebSocketService extends BaseService{
    ws: WebSocket;
    url: string;
    memberId: string;

    private heart: Subject<any> = new Subject<any>(); //监听心跳
    private message: Subject<any> = new Subject<any>(); //监听心跳

    constructor(public http: HttpClient) {
        super();
    }

    setMember(memberId: string) {
        this.memberId = memberId;
        this.url = this.BASE_WSURL;
    }

    getMember() {
        return this.memberId;
    }

    /**
     * 创建websocket
     * @param url
     */
    createObservableScoket(url: string): Observable<any> {
        this.ws = new WebSocket(this.BASE_WSURL);
        return new Observable(observer => {
            // 返回成功时执行的方法
            this.ws.onmessage = event => observer.next(event.data);
            // 返回错误时执行的方法
            this.ws.onerror = event => {
                console.log("websocket异常:" + event);
               // this.initializeWebSocket()
            };
            // 关闭websocket流时执行的方法
            // this.ws.onclose = event => observer.complete();
            this.ws.onclose = event => {
                console.log("服务器关闭了链接");
               // this.initializeWebSocket()
            };

            // this.ws.onopen = event => {
            //     return observer.next('open');
            // }
        });
    }

    /**
     *
     * @param msg 发送消息
     */
    sendMessage(msg: any) {
        msg.memberId = this.memberId;
        this.ws.send(JSON.stringify(msg));
    }

    /**
     * 初始化websocekt
     */
    initializeWebSocket() {
        this.createObservableScoket(this.url).subscribe(
            data => {
                this.analysisMessage(data);
            },
            error => {
                console.log("websoclet异常:" + error);
            },
            () => console.log("webSocket已结束!")
        );

    }

    /**
     * 返回心跳
     */
    getHeart(): Observable<any> {
        return this.heart.asObservable();
    }

    /**
     * 返回消息
     */
    getMessage(): Observable<any> {
        return this.message.asObservable();
    }

    /**
     * 关闭websocket
     */
    closeWebSocket() {
        this.ws.close();
    }

    /**
     * 发送心跳
     */
    pong() {
        // this.ws.send(AppApi.api_websocket_heart);
    }
}
 类似资料:

相关阅读

相关文章

相关问答