吉安感知网项目-前端
chenyao
21 hours ago 4c390d209b45d516fbe2f7552d26048687c83972
uniapps/work-app/src/utils/websocket.js
@@ -1,10 +1,11 @@
// WebSocket服务管理
import { useGlobalWS } from "@/hooks/useGlobalWS.js";// WebSocket服务管理
class WebSocketService {
  constructor() {
    this.socketTask = null
    this.connected = false
    this.url = ''
    this.userId = ''
    this.token = ''
    this.onMessageCallback = null
    this.onOpenCallback = null
    this.onCloseCallback = null
@@ -13,14 +14,15 @@
  }
  // 初始化WebSocket连接
  init(userId, url) {
  init(userId, url, token) {
    if (!url) {
      console.error('WebSocket初始化失败:缺少url')
      return
    }
    this.userId = userId || ''
    this.url = url + encodeURIComponent(this.userId)
    this.token = token || ''
    this.url = url
    this.connect()
  }
@@ -29,15 +31,15 @@
    try {
      // 关闭现有连接
      this.close()
      // 使用uni-app的WebSocket API
      this.socketTask = uni.connectSocket({
        url: this.url,
            protocols: [this.token],
        success: () => {
          console.log('WebSocket连接已请求')
          // console.log('WebSocket连接已请求')
        },
        fail: (error) => {
          console.error('WebSocket连接请求失败:', error)
          // console.error('WebSocket连接请求失败:', error)
          if (this.onErrorCallback) {
            this.onErrorCallback(error)
          }
@@ -47,8 +49,8 @@
      // 监听连接打开
      this.socketTask.onOpen(() => {
        this.connected = true
        console.log('WebSocket已连接,userId:', this.userId)
        this.startPing()
        // console.log('WebSocket已连接,userId:', this.userId)
        // this.startPing()
        if (this.onOpenCallback) {
          this.onOpenCallback()
        }
@@ -57,7 +59,7 @@
      // 监听连接关闭
      this.socketTask.onClose(() => {
        this.connected = false
        console.log('WebSocket已关闭')
        // console.log('WebSocket已关闭')
        this.stopPing()
        if (this.onCloseCallback) {
          this.onCloseCallback()
@@ -66,7 +68,7 @@
      // 监听连接错误
      this.socketTask.onError((error) => {
        console.error('WebSocket错误:', error)
        // console.error('WebSocket错误:', error)
        this.connected = false
        this.stopPing()
        if (this.onErrorCallback) {
@@ -78,16 +80,16 @@
      this.socketTask.onMessage((res) => {
        try {
          const message = JSON.parse(res.data)
          console.log('收到WebSocket消息:', message)
          // console.log('收到WebSocket消息:', message)
          if (this.onMessageCallback) {
            this.onMessageCallback(message)
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
          // console.error('解析WebSocket消息失败:', error)
        }
      })
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      // console.error('WebSocket连接失败:', error)
      if (this.onErrorCallback) {
        this.onErrorCallback(error)
      }
@@ -113,23 +115,24 @@
      data: JSON.stringify(message),
      success: () => {
        console.log('WebSocket消息发送成功:', message)
        // useGlobalWS();
      },
      fail: (error) => {
        console.error('WebSocket消息发送失败:', error)
        // console.error('WebSocket消息发送失败:', error)
      }
    })
  }
  // 开始心跳检测
  startPing() {
    this.stopPing()
    // 每25秒发送一次心跳
    this.pingTimer = setInterval(() => {
      if (this.connected) {
        this.send('ping', 'system')
      }
    }, 25000)
  }
  // startPing() {
  //   this.stopPing()
  //   // 每25秒发送一次心跳
  //   this.pingTimer = setInterval(() => {
  //     if (this.connected) {
  //       this.send('ping', 'system')
  //     }
  //   }, 25000)
  // }
  // 停止心跳检测
  stopPing() {
@@ -146,10 +149,10 @@
        code: 1000,
        reason: '正常关闭',
        success: () => {
          console.log('WebSocket已关闭')
          // console.log('WebSocket已关闭')
        },
        fail: (error) => {
          console.error('WebSocket关闭失败:', error)
          // console.error('WebSocket关闭失败:', error)
        }
      })
      this.socketTask = null
@@ -163,6 +166,11 @@
    this.onMessageCallback = callback
  }
  // 获取当前消息回调(用于检查是否已设置)
  getOnMessageCallback() {
    return this.onMessageCallback
  }
  // 设置连接打开回调
  setOnOpenCallback(callback) {
    this.onOpenCallback = callback