fite/lib/ws.js

52 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2023-01-17 18:43:05 +08:00
/**
2023-02-01 10:51:33 +08:00
* 一个简单到发指的 WebSocket
2023-01-17 18:43:05 +08:00
* @author yutent<yutent.io@gmail.com>
* @date 2023/01/17 17:32:51
*/
import { WebSocketServer } from 'ws'
2023-01-30 19:11:03 +08:00
class WebSocket {
2023-06-13 15:32:19 +08:00
#clients = new Map()
2023-01-30 19:11:03 +08:00
#queue = [] // 消息队列
2023-01-17 18:43:05 +08:00
2023-01-30 19:11:03 +08:00
constructor(server) {
2023-02-01 10:51:33 +08:00
if (server.listening) {
2023-05-23 18:32:24 +08:00
let conn = new WebSocketServer({ server, path: '/ws-fite-hmr' })
2023-06-13 15:32:19 +08:00
conn.on('connection', (client, req) => {
let params = new URLSearchParams(req.url.slice(req.url.indexOf('?')))
let session = params.get('session')
2023-06-26 16:39:45 +08:00
let lock = +params.get('lock')
2023-06-13 15:32:19 +08:00
2023-06-26 16:39:45 +08:00
if (lock === 1) {
client.close()
} else {
this.#clients.set(session, client)
2023-06-13 15:32:19 +08:00
2023-06-26 16:39:45 +08:00
client.once('close', _ => {
this.#clients.delete(session)
})
2023-06-13 15:32:19 +08:00
2023-06-26 16:39:45 +08:00
while (this.#queue.length) {
let msg = this.#queue.shift()
this.send(msg)
}
2023-02-01 10:51:33 +08:00
}
})
}
2023-01-30 19:11:03 +08:00
}
send(msg = {}) {
2023-06-13 15:32:19 +08:00
if (this.#clients.size) {
for (let [key, client] of this.#clients) {
2023-06-13 15:32:19 +08:00
client.send(JSON.stringify(msg))
}
2023-01-30 19:11:03 +08:00
} else {
this.#queue.push(msg)
}
}
}
export default function (server) {
return new WebSocket(server)
2023-01-17 18:43:05 +08:00
}