stomp.js 1.77 KB
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
  
let stompClient = null
const getStompClient = function () {
  if (stompClient === null) {
    let socket = new SockJS('https://openday.console.etoneiot.tech/openday-boot/realtime')
    stompClient = Stomp.over(socket)
    stompClient.hasDebug = false
  }
  return stompClient
}
/**
         * 连接服务
         * @param  [{ topic: String, callback: Function}]
         */
const connect = function (params) {
  let client = getStompClient()
  if (client.connected) {
    return
  }
  let onConnected = function (frame) {
    for (const param of params) {
      if (!param.type) {
        param.type = 'subscribe'
      }
      if (param.type === 'subscribe') {
        client.subscribe(param.topic, param.callback)
      }
      if (param.type === 'send') {
        if (!param.payload) {
          param.payload = ""
        }
        client.send(param.topic, param.payload)
      }
      if (param.type === 'callback' && param.callback) {
        param.callback(client)
      }
    }
  }
  client.connect({}, onConnected, (frame) => {
    //自动重连
    setTimeout(() => {
      let socket = new SockJS('/openday-boot/realtime')
      stompClient = Stomp.over(socket)
      stompClient.hasDebug = false
      connect(params)
    }, 2000)
  })
}
const disconnect = function () {
  if (stompClient && stompClient.connected) {
    stompClient.disconnect()
    stompClient = null
  }
}
const sendMessage = function (topic, message) {
  if (stompClient && stompClient.connected) {
    let msg = message
    if (typeof msg !== 'string') {
      msg = JSON.stringify(msg)
    }
    stompClient.send(topic, msg)
  } else {
    throw 'stomp client is null or disconnected'
  }
}

export default {
  connect,
  disconnect,
  sendMessage
}