import { MTP2WebSocket } from '../../utils/websocket/index' import { SendMessage } from '../../utils/websocket/interface' import { Package40, Package50 } from '../../utils/websocket/package' import { timerInterceptor } from '../../utils/timer/index' import { FunCode } from '../../constants/enum/funcode' import { parseReceivePush } from './quote/build/decode' import service from '../../services/index' import eventBus from '../bus/index' /** * 全局数据连接生命周期控制类 */ export default new (class { /** 行情服务 */ private readonly quoteServer = new MTP2WebSocket(Package40); /** 交易服务 */ private readonly tradeServer = new MTP2WebSocket(Package50); constructor() { this.quoteServer.onPush = (p: any) => { const { mainClassNumber, content } = p; if (mainClassNumber === 65 && content) { const result = parseReceivePush(content); // 通知上层 行情推送 eventBus.$emit('quotePushNotify', result); } } this.quoteServer.onReconnect = () => { // 通知上层 重新订阅商品 eventBus.$emit('quoteServerReconnectNotify'); } this.tradeServer.onPush = ({ funCode }) => { const delay = 1000; // 延迟推送消息,防止短时间内重复请求 switch (funCode) { case FunCode.MoneyChangedNotify: { timerInterceptor.debounce(() => { // 通知上层 资金变动 eventBus.$emit('moneyChangedNotify'); }, delay, funCode.toString()) break; } default: { if (funCode) { console.warn('接收到未定义的通知', funCode); } } } } } /** 主动连接行情服务 */ connectQuote(callback?: () => void) { service.onReady(() => { const { quoteUrl } = service.config; this.quoteServer.connect(quoteUrl).then(() => { callback && callback(); }) }) } /** 主动连接交易服务 */ connectTrade(callback?: () => void) { service.onReady(() => { const { tradeUrl } = service.config; this.tradeServer.connect(tradeUrl).then(() => { callback && callback(); }) }) } /** 向行情服务器发送请求 */ sendQuoteServer(msg: SendMessage) { this.connectQuote(() => this.quoteServer.send(msg)); } /** 向交易服务器发送请求 */ sendTradeServer(msg: SendMessage) { this.connectTrade(() => this.tradeServer.send(msg)); } /** 主动关闭行情服务 */ closeQuoteServer() { this.quoteServer.close(); } /** 主动关闭交易服务 */ closeTradeServer() { this.tradeServer.close(); } })