socket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // src/utils/socket.js
  2. import { ElMessage } from 'element-plus'
  3. import { ROOTPATH2 } from '../comment/httpUrl.js'
  4. var WSS = null // 全局唯一的 WebSocket 实例
  5. /**
  6. * 连接 WebSocket
  7. * @param {string} userId 当前用户 ID
  8. */
  9. export function connectSocket(userId, store, router) {
  10. if (!userId) return
  11. // 若已有连接则关闭
  12. if (WSS) {
  13. try {
  14. WSS.close()
  15. } catch { }
  16. }
  17. let tabId = sessionStorage.getItem('tabId');
  18. if (!tabId) {
  19. tabId = Date.now() + '_' + Math.random().toString(36).slice(2);
  20. sessionStorage.setItem('tabId', tabId);
  21. }
  22. const wsUrl = `${ROOTPATH2}${userId}?tabId=${tabId}`
  23. WSS = new WebSocket(wsUrl)
  24. console.log('🔗 WebSocket 连接中:', wsUrl)
  25. console.log(WSS)
  26. WSS.onopen = () => {
  27. console.log('✅ WebSocket 已连接:', wsUrl)
  28. }
  29. WSS.onmessage = (event) => {
  30. if (event.data === 'HeartBeat') return
  31. let msg
  32. try {
  33. msg = JSON.parse(event.data)
  34. } catch (e) {
  35. console.warn('非 JSON 消息:', event.data)
  36. return
  37. }
  38. if (msg.type === 'kickOut') {
  39. ElMessage({
  40. message: msg.content || '您的账号已在其他设备登录',
  41. type: 'warning',
  42. duration: 1500
  43. })
  44. // 清空本地存储
  45. localStorage.removeItem('token')
  46. localStorage.removeItem('userId')
  47. localStorage.removeItem('userType')
  48. localStorage.removeItem('companyId')
  49. if (store) store.dispatch('SET_DATA')
  50. if (router) router.push({ name: 'login' })
  51. }
  52. }
  53. WSS.onerror = (err) => {
  54. console.error('❌ WebSocket 错误:', err)
  55. }
  56. WSS.onclose = () => {
  57. console.log('🔌 WebSocket 已关闭')
  58. }
  59. }
  60. /** 获取 WebSocket 实例 */
  61. export function getSocket() {
  62. return WSS
  63. }
  64. /** 发送消息 */
  65. export function sendSocketMsg(data) {
  66. if (WSS && WSS.readyState === WebSocket.OPEN) {
  67. WSS.send(data)
  68. } else {
  69. console.warn('⚠️ WebSocket 未连接,无法发送')
  70. }
  71. }
  72. /** 关闭连接 */
  73. export function closeSocket() {
  74. if (WSS) {
  75. WSS.close()
  76. WSS = null
  77. }
  78. }