stomp.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Client } from '@stomp/stompjs'
  2. import { isObject, get } from 'lodash-es'
  3. let client
  4. const options = {
  5. brokerURL: 'ws://localhost:15674/ws',
  6. connectHeaders: {
  7. host: 'hxmsg',
  8. login: 'huaxin',
  9. passcode: '1234qwerasdf'
  10. },
  11. reconnectDelay: 5000,
  12. heartbeatIncoming: 4000,
  13. heartbeatOutgoing: 4000
  14. }
  15. /**
  16. * 初始化stomp并订阅指定地址
  17. * @param {Object} subscribes 订阅配置 {[url]:(msg)=>{}} key:订阅地址;value:回调函数
  18. * @returns
  19. */
  20. const initClient = (subscribes) => {
  21. client = new Client(options)
  22. client.onConnect = (res) => {
  23. console.log('is connected')
  24. if (!isObject(subscribes)) return
  25. for (const url in subscribes) {
  26. const cb = subscribes[url]
  27. client.subscribe(url, (msg) => {
  28. let body = get(msg, 'body')
  29. if (body) body = JSON.parse(body)
  30. cb(body)
  31. })
  32. }
  33. }
  34. client.onStompError = (res) => {
  35. console.log('connect error')
  36. console.log(res)
  37. }
  38. client.activate()
  39. return client
  40. }
  41. export { initClient }