3 changed files with 74 additions and 61 deletions
@ -0,0 +1,40 @@ |
|||
import { broadcast } from '../utils/websocket.js' |
|||
|
|||
export const debugRoutes = (app) => { |
|||
const statusList = ['info', 'warn', 'success', 'error', 'finish'] |
|||
|
|||
app.post('/api/debug/cmd', (req, res) => { |
|||
const { commandId, command, params } = req.body |
|||
console.log('收到命令:', command, '参数:', params) |
|||
|
|||
// 模拟返回数据
|
|||
const mockResponse = { |
|||
code: '0', |
|||
msg: '成功', |
|||
data: null, |
|||
} |
|||
|
|||
let messageNum = 0 |
|||
|
|||
// 异步广播消息
|
|||
setTimeout(() => { |
|||
res.json(mockResponse) |
|||
const poll = setInterval(() => { |
|||
if (messageNum === 10) { |
|||
clearInterval(poll) |
|||
} |
|||
broadcast({ |
|||
type: 'cmd_debug', |
|||
data: { |
|||
commandId, |
|||
command, |
|||
status: statusList[Math.floor(Math.random() * statusList.length)], |
|||
title: `步骤${messageNum}执行完成`, |
|||
content: `具体信息${messageNum}`, |
|||
}, |
|||
}) |
|||
messageNum++ |
|||
}, Math.floor(Math.random() * (1000 - 500 + 1)) + 500) |
|||
}, 1000) |
|||
}) |
|||
} |
@ -0,0 +1,28 @@ |
|||
import { WebSocketServer } from 'ws' |
|||
|
|||
export const clients = new Set() |
|||
|
|||
export const broadcast = (message) => { |
|||
try { |
|||
const jsonMessage = JSON.stringify(message) |
|||
clients.forEach((client) => { |
|||
if (client.readyState === WebSocket.OPEN) { |
|||
client.send(jsonMessage) |
|||
} |
|||
}) |
|||
} |
|||
catch (e) { |
|||
console.log('广播发送失败:', e, message) |
|||
} |
|||
} |
|||
|
|||
export const initWebSocketServer = () => { |
|||
const wss = new WebSocketServer({ port: 9527 }) |
|||
|
|||
wss.on('connection', (ws) => { |
|||
clients.add(ws) |
|||
ws.on('close', () => { |
|||
console.log('客户端断开') |
|||
}) |
|||
}) |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue