websocket系统消息

1. 创建WebSocket工具类 (`src/libs/websocket.js`)

websocket.js

class SocketService {

static instance = null

callbackMapping = {}

static get Instance() {

if (!this.instance) {

this.instance = new SocketService() } return this.instance

}

connect(url) {

this.socket = new WebSocket(url)

this.socket.onopen = () => { console.log('WebSocket连接成功') this.heartbeat() }

this.socket.onmessage = msg => { const data = JSON.parse(msg.data)

const callback = this.callbackMapping[data.type] callback && callback(data) }

this.socket.onclose = () => { console.log('WebSocket断开连接') setTimeout(() => this.connect(url), 5000) } }

// 心跳检测 heartbeat() { this.timer = setInterval(() => { this.socket.send(JSON.stringify({ type: 'heartbeat' })) }, 30000) }

// 注册回调 registerCallback(type, callback) { this.callbackMapping[type] = callback }

// 发送消息 send(data) { this.socket.send(JSON.stringify(data)) }

// 关闭连接 close() { clearInterval(this.timer) this.socket.close() } }

export const socket = SocketService.Instance

2. 在Vue中初始化连接 (`src/main.js`)

 

import { socket } from '@/libs/websocket'

// 根据环境变量配置WS地址 const wsUrl = process.env.NODE_ENV === 'production' ? `wss://${window.location.host}/ws` : 'ws://localhost:8080/ws' socket.connect(wsUrl)

3. 消息接收处理 (`src/views/layout/components/Navbar.vue`)

import { socket } from '@/libs/websocket'

export default {

mounted() {

// 注册消息回调 socket.registerCallback('notification', data => {

this.$notify({ title: '系统消息', message: data.content, type: data.level || 'info' }) }) },

beforeDestroy() {

socket.close()

}

}

 4. 后端接口示例 (Node.js)

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {

console.log('客户端已连接')

ws.on('message', message => {

const data = JSON.parse(message)

if (data.type === 'heartbeat') return

// 业务消息处理 if (data.type === 'subscribe') {

setInterval(() => { ws.send(JSON.stringify({ type: 'notification', content: '您有新的待办事项', level: 'warning' })) }, 10000) } }) })

5. 生产环境配置 (`vue.config.js`)

module.exports = {

devServer: {

proxy: { '/ws': { target: 'http://localhost:8080', ws: true, // 启用WebSocket代理 changeOrigin: true }

}

}

}

 

posted @ 2025-04-24 11:48  世界险恶你要内心强大  阅读(18)  评论(0)    收藏  举报