index.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { MTP2WebSocket } from '../../utils/websocket/index'
  2. import { SendMessage } from '../../utils/websocket/interface'
  3. import { Package40, Package50 } from '../../utils/websocket/package'
  4. import { timerInterceptor } from '../../utils/timer/index'
  5. import { FunCode } from '../../constants/enum/funcode'
  6. import { parseReceivePush } from './quote/build/decode'
  7. import service from '../../services/index'
  8. import eventBus from '../bus/index'
  9. /**
  10. * 全局数据连接生命周期控制类
  11. */
  12. export default new (class {
  13. /** 行情服务 */
  14. private readonly quoteServer = new MTP2WebSocket(Package40);
  15. /** 交易服务 */
  16. private readonly tradeServer = new MTP2WebSocket(Package50);
  17. constructor() {
  18. this.quoteServer.onPush = (p: any) => {
  19. const { mainClassNumber, content } = p;
  20. if (mainClassNumber === 65 && content) {
  21. const result = parseReceivePush(content);
  22. // 通知上层 行情推送
  23. eventBus.$emit('quotePushNotify', result);
  24. }
  25. }
  26. this.quoteServer.onReconnect = () => {
  27. // 通知上层 重新订阅商品
  28. eventBus.$emit('quoteServerReconnectNotify');
  29. }
  30. this.tradeServer.onPush = ({ funCode }) => {
  31. const delay = 1000; // 延迟推送消息,防止短时间内重复请求
  32. switch (funCode) {
  33. case FunCode.MoneyChangedNotify: {
  34. timerInterceptor.debounce(() => {
  35. // 通知上层 资金变动
  36. eventBus.$emit('moneyChangedNotify');
  37. }, delay, funCode.toString())
  38. break;
  39. }
  40. default: {
  41. if (funCode) {
  42. console.warn('接收到未定义的通知', funCode);
  43. }
  44. }
  45. }
  46. }
  47. }
  48. /** 主动连接行情服务 */
  49. connectQuote(callback?: () => void) {
  50. service.onReady(() => {
  51. const { quoteUrl } = service.config;
  52. this.quoteServer.connect(quoteUrl).then(() => {
  53. callback && callback();
  54. })
  55. })
  56. }
  57. /** 主动连接交易服务 */
  58. connectTrade(callback?: () => void) {
  59. service.onReady(() => {
  60. const { tradeUrl } = service.config;
  61. this.tradeServer.connect(tradeUrl).then(() => {
  62. callback && callback();
  63. })
  64. })
  65. }
  66. /** 向行情服务器发送请求 */
  67. sendQuoteServer(msg: SendMessage<Package40>) {
  68. this.connectQuote(() => this.quoteServer.send(msg));
  69. }
  70. /** 向交易服务器发送请求 */
  71. sendTradeServer(msg: SendMessage<Package50>) {
  72. this.connectTrade(() => this.tradeServer.send(msg));
  73. }
  74. /** 主动关闭行情服务 */
  75. closeQuoteServer() {
  76. this.quoteServer.close();
  77. }
  78. /** 主动关闭交易服务 */
  79. closeTradeServer() {
  80. this.tradeServer.close();
  81. }
  82. })