loms_web项目websocket的应用

先封装websocket: 

import WsServer from '../standard-business/wsServer';
import {host} from './globalConfig';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

class WebSocketProxy {
  constructor() {
    this.sockets = {};
    this.stomps = {};
  }

  sendMessageToBrowser(token, message) {
    const sockets = this.sockets[token] || [];
    for (const ws of sockets) {
      WsServer.sendMessage(ws, 'global', message);
    }
  }

  stompDisconnect(token) {
    const sockets = this.sockets[token] || [];
    this.stomps[token] = null;
    this.sockets[token] = null;
    for (const ws of sockets) {
      ws.close();
    }
  }

  createStompClient(token) {
    const path = `${host}/epld-websocket`;
    const sock = new SockJS(path, null, {'transports': ['websocket']});
    const stompClient = Stomp.over(sock);
    this.stomps[token] = stompClient;

    const onConnect = () => {
      console.log('stomp connect 成功');
      stompClient.subscribe('/user/queue/notifications', ({body}) => {
        try {
          const data = JSON.parse(body);
          data.senderInfo = JSON.parse(data.senderInfo);
          this.sendMessageToBrowser(token, data);
        } catch (e) {
          console.log(e);
        }
      });
    };

    const onError = (error) => {
      console.log(error);
      this.stompDisconnect(token);
    };

    stompClient.connect({token}, onConnect, onError);
  }

  webSocketClosed(ws) {
    const token = ws.token;
    const sockets = this.sockets[token];
    if (sockets) {
      this.sockets[token] = sockets.filter(socket => socket !== ws);
      if (!this.sockets[token].length) {
        this.sockets[token] = null;
        if (this.stomps[token]) {
          try {
            this.stomps[token].disconnect();
          } catch (e) {
            console.log('webSocketClosed 捕获异常');
            this.stomps[token] = null;
          }
        }
      }
    }
  }

  addWebSocket(ws) {
    const token = ws.token;
    if (token) {
      if (this.sockets[token]) {
        this.sockets[token].push(ws);
      } else {
        this.sockets[token] = [];
        this.sockets[token].push(ws);
        this.createStompClient(token);
      }

      ws.on('close', () => {
        console.log(`${ws.username}(token:${ws.token}) disconnection`);
        this.webSocketClosed(ws);
      });
    }
  }
}

export default WebSocketProxy;

在同构的服务器端构造代码里加入websocket服务器: 

// 建立WS服务器
const wsProxy = new WebSocketProxy();
const wsServer = WsServer.createServer(server);
wsServer.onConnect(ws => wsProxy.addWebSocket(ws));

 全局调用:

const msgConfig = [
  {title: '系统消息', url: '/message/msg_system'},
  {title: '订单消息', url: '/message/msg_order'},
  {title: '派单消息', url: '/message/msg_dispatch'},
  {title: '跟踪消息', url: '/message/msg_track'},
  {title: '异常消息', url: '/message/msg_abnormal'},
];

const showGlobalMessage = (type=0, message) => {
  const config = msgConfig[type];
  const key = new Date().getTime();
  notification.open({
    key,
    message: config.title,
    description: <Link to={config.url} onClick={() => notification.close(key)}>{message}</Link>,
    duration: 10,
    placement: 'bottomRight',
    style: {
      whiteSpace: 'pre'
    }
  });
};

// 建立WS连接
const connectWsServer = () => {
  const wsClient = getWsClient();
  wsClient.onMessage('global', ({body}) => {
    showGlobalMessage(body.type, body.content);
  });
};

 

转载于:https://my.oschina.net/u/3288561/blog/2239872

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值