写过一篇 发表于 2026-2-11 16:06:38

WebSocket

export default class MessageSocket {
constructor(url) {
    this.url = url
    this.ws = null
    this.count = 0
    this.status = false
    this.interval = null
}

init() {
    if (typeof WebSocket) {
      this.interval && clearInterval(this.interval)
      if (this.status) return
      this.ws = new WebSocket(this.url)

      this.ws.onopen = () => {
      this.status = true
      this.count = 0
      console.log('WebSocket连接成功')

      this.interval = setInterval(() => {
          this.ws.send(JSON.stringify({ type: 'heartbeat' }))
      }, 30 * 1000)
      }

      this.ws.onclose = () => {
      this.status = false
      console.log('WebSocket连接关闭')

      if (this.count < 10) {
          setTimeout(() => {
            this.init()
            this.count++
            console.log(`webSocket连接失败,正在尝试第${this.count}次重连...`)
          }, 5000)
      }
      }

      this.ws.onerror = (error) => {
      console.log('WebSocket连接错误', error)
      this.status = false

      if (this.count < 10) {
          setTimeout(() => {
            this.init()
            this.count++
            console.log(`webSocket连接失败,正在尝试第${this.count}次重连...`)
          }, 5000)
      }
      }

      return this.ws
    } else {
      this.$message.error('该浏览器不支持WebSocket通信')
    }
}
}
import MessageSocket from '@/api/socket.js'
// 初始化WebSocket连接
function initWebSocket() {
try {
    console.log(window.location)
    // 根据环境和协议生成WebSocket URL
    const isProduction = process.env.NODE_ENV === 'production'
    const isHttps = window.location.protocol === 'https:'

    let url
    if (isProduction) {
      // 生产环境
      url = isHttps
      ? `wss://${window.location.hostname}/sppds/websocket/vehicle`
      : `ws://${window.location.host}/sppds/websocket/vehicle`
    } else {
      // 开发环境
      url = 'ws://10.186.131.62:8082/sppds/websocket/vehicle'
    }

    console.log('WebSocket URL:', url)
    const webSocket = new MessageSocket(url).init()
    webSocket.onmessage = onmessage
} catch (error) {
    console.log('WebSocket 连接失败:', error)
}
}
// 初始化WebSocket连接
initWebSocket()

// 处理WebSocket消息
function onmessage(e) {
try {
    const wsAlarmInfo = JSON.parse(e.data)
    console.log(wsAlarmInfo, 'webSocket onmessage')
} catch (error) {
    console.log('webSocket onmessage error:', error)
}
}

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
页: [1]
查看完整版本: WebSocket