WebSocket 实现实时消息推送

2023-04-19  本文已影响0人  云上笔记
// 安装依赖包
npm install @stomp/stompjs
npm install sockjs-client

// websocket
import { Stomp } from '@stomp/stompjs';
import * as SockJS from 'sockjs-client';

private host: string = environment.service; 
public stompClient = null;

  ngOnInit(): void {
    this.connectSocket();
  }

  ngOnDestroy() {
    this.disconnectSocket();
  }

  /**
   * websocket 监听交易的工作流状态是否改变,若服务器有返回root_id,则弹出消息提示并刷新页面
   */
  private connectSocket() {
    // 与广播节点建立连接
    const socket = new SockJS(`${this.host}/workflow/notifications`);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, (frame: any) => {
      // 订阅主题  /notifications/process-instance
      this.stompClient.subscribe(
        '/workflow/notifications/process-trade',
        (message: { body: string }) => {
          // 服务器返回消息
          console.log(JSON.parse(message.body));
        }
      );
    });
  }

  private disconnectSocket() {
    if (this.stompClient != null) {
      this.stompClient.disconnect();
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读