Files
dvcp-node-service/src/websocket/index.js
2023-02-16 17:05:35 +08:00

35 lines
1.1 KiB
JavaScript

const {findFile} = require("../utils/fsUtils");
const chalk = require("chalk");
const dayjs = require("dayjs");
const {checkJson} = require("../tools");
const {log} = console
module.exports = {
init: ins => new Promise(resolve => {
let actions = {}
findFile('./src/websocket', file => {
if (!/index\.js/.test(file)) {
const item = require(file.replace(/src[\\\/]websocket/, '.'))
actions[item.action] = item.execute
}
}).then(() => {
ins.ws('/ws', ws => {
log(`${chalk.bgBlue.black(" WEBSOCKET ")} 服务已启动!`)
ws.send('您已成功连接到node websocket')
ws.onerror = () => ws.close()
ws.on('close', () => {
log(`${chalk.bgRed.black(" WEBSOCKET ")} 连接已断开!`)
clearInterval(heartBeat)
})
ws.on('message', res => {
if (checkJson(res)) {
const data = JSON.parse(res)
!!data?.action && actions[data.action]?.(ws, data)
}
})
let heartBeat = setInterval(() => ws.send(`heartBeat at ${dayjs().format("YYYY-MM-DD HH:mm:ss")}`), 5000)
resolve()
})
})
})
}