angular中webSocket的使用

马浩淼
2023-12-01

使用这个:
https://www.cnblogs.com/fengguohoudejiyi/p/8531542.html

wesocket.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class WebSocketService {
    ws: WebSocket;
    constructor() { }
    // 返回一个可观测的流,包括服务器返回的消息
    createObservableSocket(url: string): Observable<any> {
        this.ws = new WebSocket(url);
        return new Observable(
            observer => {
                this.ws.onmessage = (event) => observer.next(event.data);  // 成功,返回数据
                this.ws.onerror = (event) => observer.error(event); // 失败
                this.ws.onclose = (event) => observer.complete(); // 完成后,要结束

            })
    }
    // 向服务器端发送消息
    sendMessage(message: any) {
        let that = this
        // console.log(this.ws)
        if(this.ws){
            if (this.ws.readyState===1) {
                this.ws.send(JSON.stringify(message));
            }else{
                // console.log(this.ws.readyState)
            }
        }else{
        	// socket可能还没连接成功,那么延迟一秒再发送消息
            setTimeout(function () {
                that.ws.send(JSON.stringify(message));
            },1000)
        }
    }
}        

使用:

// 格式:ws://10.xx.xx.xx:8088/ws
// 初始化,先创建socket的连接
initSocket(){
 	this.wsService.createObservableSocket("ws" + str + "/ws").subscribe(
          data => {
            this.upOut(data); // 成功后的回调函数
          },
          err => console.log(err),
          () => console.log("流已经结束") //  最后结束后,会执行到这的
        );
}


// click事件后执行发送消息:
sendSocket() {
	this.wsService.sendMessage({
      key1: "key111", // 参数
      key2: "key222",
    });

}

参考:https://www.cnblogs.com/changyaoself/p/8296122.html

 类似资料: