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

  1. // const express = require('express')
  2. import express from 'express'
  3. import { WebSocketServer } from 'ws'
  4. const app = express()
  5. const PORT = 8080 // 可根据需要更改端口号
  6. app.listen(PORT, () => {
  7. console.log(`服务器已启动,正在监听端口 ${PORT}`)
  8. })
  9. app.use(express.json())
  10. const levels = ['info', 'warn', 'success', 'error', 'finish']
  11. app.post('/api/debug/cmd', (req, res) => {
  12. const { commandId, command, params } = req.body
  13. console.log('收到命令:', command, '参数:', params)
  14. // 模拟返回数据
  15. const mockResponse = {
  16. code: '0',
  17. msg: '成功',
  18. data: null,
  19. }
  20. let messageNum = 0
  21. // 异步广播消息
  22. setTimeout(() => {
  23. res.json(mockResponse)
  24. const poll = setInterval(() => {
  25. if (messageNum === 10) {
  26. clearInterval(poll)
  27. }
  28. broadcast({
  29. type: 'notification',
  30. data: {
  31. commandId,
  32. command,
  33. level: levels[Math.floor(Math.random() * levels.length)],
  34. title: `步骤${messageNum}执行完成`,
  35. content: `具体信息${messageNum}`,
  36. dateTime: new Date().toLocaleString(),
  37. },
  38. })
  39. messageNum++
  40. }, Math.floor(Math.random() * (1000 - 500 + 1)) + 500)
  41. }, 1000)
  42. })
  43. const wss = new WebSocketServer({ port: 9527 })
  44. const clients = new Set()
  45. wss.on('connection', (ws) => {
  46. clients.add(ws)
  47. ws.on('close', () => {
  48. console.log('客户端断开')
  49. })
  50. })
  51. function broadcast(message) {
  52. try {
  53. const jsonMessage = JSON.stringify(message)
  54. clients.forEach((client) => {
  55. if (client.readyState === WebSocket.OPEN) {
  56. client.send(jsonMessage)
  57. }
  58. })
  59. }
  60. catch (e) {
  61. console.log('广播发送失败:', e, message)
  62. }
  63. }