HcSocket.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import website from '~src/config/index'
  2. import { isNullES } from 'js-fast-way'
  3. // 长链接推送插件
  4. export default class HcSocket {
  5. static socket = null
  6. static create(data, change) {
  7. const socket = new WebSocket(website.socket + data)
  8. socket.onopen = function () {
  9. console.log('websocket 链接成功')
  10. }
  11. socket.onclose = function () {
  12. console.log('websocket 链接已断开')
  13. }
  14. socket.onmessage = function ({ data }) {
  15. if (typeof change !== 'function') {
  16. return false
  17. } else {
  18. change(JSON.parse(data))
  19. }
  20. }
  21. socket.onerror = function ({ data }) {
  22. console.log('websocket 发生错误:', data)
  23. }
  24. this.socket = socket
  25. }
  26. //发送消息
  27. static async send(data) {
  28. const is_socket = await this.isSocket()
  29. if (!is_socket) return false
  30. this.socket.send(data)
  31. }
  32. //链接是否存在
  33. static async isSocket(i = 0) {
  34. let _this = this
  35. return new Promise((resolve) => {
  36. if (isNullES(_this.socket)) {
  37. if (i <= 30) {
  38. setTimeout(async () => {
  39. i++
  40. resolve(await _this.isSocket(i))
  41. }, 1000)
  42. } else {
  43. resolve(false)
  44. }
  45. } else {
  46. resolve(true)
  47. }
  48. })
  49. }
  50. }