socket-instance.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import WsSocket from '@/utils/ws/ws-socket'
  2. import { getToken } from '@/utils/auth'
  3. import { Notification } from 'element-ui'
  4. /**
  5. * SocketInstance 连接实例
  6. *
  7. * 注释: 所有 WebSocket 消息接收处理在此实例中处理
  8. */
  9. class SocketInstance {
  10. /**
  11. * WsSocket 实例
  12. */
  13. socket
  14. /**
  15. * SocketInstance 初始化实例
  16. */
  17. constructor() {
  18. this.socket = new WsSocket(
  19. () => {
  20. const token = getToken()
  21. if (token === null || token === '') {
  22. return null
  23. } else {
  24. return 'ws://push.reghao.cn/ws/push?token=' + token
  25. }
  26. },
  27. {
  28. onError: evt => {
  29. console.log('Websocket 连接失败回调方法')
  30. },
  31. // Websocket 连接成功回调方法
  32. onOpen: evt => {
  33. // 更新 WebSocket 连接状态
  34. console.log('ws 连接成功')
  35. },
  36. // Websocket 断开连接回调方法
  37. onClose: evt => {
  38. // 更新 WebSocket 连接状态
  39. console.log('ws 连接断开')
  40. }
  41. }
  42. )
  43. this.registerEvents()
  44. }
  45. // 连接 WebSocket 服务
  46. connect() {
  47. this.socket.connection()
  48. }
  49. /**
  50. * 注册回调消息处理事件
  51. */
  52. registerEvents() {
  53. this.socket.on('heartbeat', data => {})
  54. this.socket.on('censorVideo', data => {
  55. console.log('----------')
  56. console.log(data)
  57. Notification({
  58. title: '友情提示',
  59. message: data,
  60. type: 'warning',
  61. duration: 3000
  62. })
  63. })
  64. this.socket.on('event_error', data => {
  65. Notification({
  66. title: '友情提示',
  67. message: data.message,
  68. type: 'warning'
  69. })
  70. })
  71. }
  72. /**
  73. * 聊天发送数据
  74. *
  75. * @param {Object} mesage
  76. */
  77. send(mesage) {
  78. this.socket.send(mesage)
  79. }
  80. /**
  81. * 推送消息
  82. *
  83. * @param {String} event 事件名
  84. * @param {Object} data 数据
  85. */
  86. emit(event, data) {
  87. this.socket.emit(event, data)
  88. }
  89. }
  90. export default new SocketInstance()