WebSocket 实现实时消息推送

// 安装依赖包
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();
    }
  }

版权声明:
作者:Mr李
链接:https://www.techfm.club/p/44001.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>