You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.7 KiB
73 lines
1.7 KiB
// const express = require('express')
|
|
import express from 'express'
|
|
import { WebSocketServer } from 'ws'
|
|
|
|
const app = express()
|
|
|
|
const PORT = 8080 // 可根据需要更改端口号
|
|
app.listen(PORT, () => {
|
|
console.log(`服务器已启动,正在监听端口 ${PORT}`)
|
|
})
|
|
app.use(express.json())
|
|
|
|
const levels = ['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: 'notification',
|
|
data: {
|
|
commandId,
|
|
command,
|
|
level: levels[Math.floor(Math.random() * levels.length)],
|
|
title: `步骤${messageNum}执行完成`,
|
|
content: `具体信息${messageNum}`,
|
|
dateTime: new Date().toLocaleString(),
|
|
},
|
|
})
|
|
messageNum++
|
|
}, Math.floor(Math.random() * (1000 - 500 + 1)) + 500)
|
|
}, 1000)
|
|
})
|
|
|
|
const wss = new WebSocketServer({ port: 9527 })
|
|
|
|
const clients = new Set()
|
|
wss.on('connection', (ws) => {
|
|
clients.add(ws)
|
|
ws.on('close', () => {
|
|
console.log('客户端断开')
|
|
})
|
|
})
|
|
|
|
function 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)
|
|
}
|
|
}
|