55 lines
2.4 KiB
JavaScript
55 lines
2.4 KiB
JavaScript
import express from 'express'
|
|
import expressWs from 'express-ws'
|
|
|
|
const app = express()
|
|
const wsInstance = expressWs(app)
|
|
app.use(express.static('dist'))
|
|
app.use(express.json())
|
|
|
|
app.ws('/online', (ws, req) => {
|
|
ws.id = req.headers['sec-websocket-key']
|
|
ws.channel = req.params.channel
|
|
ws.name = req.query.name
|
|
console.log('ws.name:', ws.name)
|
|
ws.on('close', () => {
|
|
console.log(ws.id, '设备离开频道:', ws.channel, wsInstance.getWss().clients.size)
|
|
})
|
|
ws.on('error', () => {
|
|
console.log(ws.id, '设备发生错误:', ws.channel, wsInstance.getWss().clients.size)
|
|
})
|
|
ws.on('message', message => {
|
|
console.log(ws.id, '设备发送消息:', ws.channel, wsInstance.getWss().clients.size)
|
|
const data = JSON.parse(message)
|
|
console.log('message:', data)
|
|
|
|
// 设备告知伺服器开始为某些资源做种
|
|
// 服务器不参与设备之间通信, 只作有效性统计
|
|
// 设备与8个设备建立连接
|
|
// 连接不足时, 向剩余设备请求邻接表
|
|
// 从邻接表中选择合适的设备建立连接
|
|
// 请求资源时, 遍历每次向随机2个设备询问, 如果不提供, 则向邻接表中的设备询问
|
|
// 如果命中率低, 考虑扩大连接表, 命中率足够时, 考虑缩小连接表
|
|
// 总之先统计资源分布情况
|
|
// 设备获取某些资源的分布节点 -> 随后设备自行连接节点获取数据
|
|
})
|
|
//// 设备加入频道时广播给所有在线设备(也获取所有在线设备)
|
|
//console.log(ws.id, '设备加入频道:', ws.channel, wsInstance.getWss().clients.size)
|
|
//const list = []
|
|
//wsInstance.getWss().clients.forEach(client => {
|
|
// if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
|
|
// console.log(ws.name, '广播给在线设备:', client.name)
|
|
// client.send(JSON.stringify({ type: 'push', user: { id: ws.id, name: ws.name }, channel: ws.channel }))
|
|
// list.push({ id: client.id, name: client.name })
|
|
// }
|
|
//})
|
|
//ws.send(JSON.stringify({ type: 'list', list }))
|
|
})
|
|
|
|
// WEBHOOK 处理 Git 事件
|
|
app.post('/webhook', (req, res) => {
|
|
console.log('WEBHOOK:' + new Date().toLocaleString())
|
|
exec('git pull;npm i;npm run build')
|
|
return res.json({ success: true })
|
|
})
|
|
|
|
app.listen(9999, () => console.log('Server started on port 9999')) |