const express = require('express')
const expressWs = require('express-ws')
const app = express()
expressWs(app)
const prot = 8001 // 启动端口
const server = require('./server/server')
app.use('/test', server)
// 长连接
const ws = require('./server/ws')
app.use('/ws', ws)
app.listen(prot, err => {
if (!err) console.log(`服务启动成功 http://localhost:${prot}`)
})
const express = require('express')
const expressWs = require('express-ws')
const XEUtils = require('xe-utils')
const router = express.Router()
expressWs(router)
// 用户列表
let users = []
router.ws('/socketTest/:id', (ws, req) => {
const id = req.params.id
users.push({
id,
ws
}) // 用户统一连接
console.log(id + ' 用户,进入')
// 接收消息
ws.on('message', msg => {
// 消息群发
users.forEach(e => e.ws.send(msg))
})
// 退出聊天室
ws.on('close', () => {
XEUtils.remove(users, e => e.id === id)
console.log(id, ' 用户,退出')
})
})
module.exports = router