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 {
|
|
|
|
#ws = null // ws实例
|
|
|
|
#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) {
|
|
|
|
let conn = new WebSocketServer({ server, path: '/ws-vue-live' })
|
|
|
|
conn.on('connection', ws => {
|
|
|
|
this.#ws = ws
|
|
|
|
// ws.on('message', data => {
|
|
|
|
// console.log(data + '');
|
|
|
|
// })
|
|
|
|
while (this.#queue.length) {
|
|
|
|
let msg = this.#queue.shift()
|
|
|
|
this.send(msg)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2023-01-30 19:11:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
send(msg = {}) {
|
|
|
|
if (this.#ws) {
|
|
|
|
this.#ws.send(JSON.stringify(msg))
|
|
|
|
} else {
|
|
|
|
this.#queue.push(msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function (server) {
|
|
|
|
return new WebSocket(server)
|
2023-01-17 18:43:05 +08:00
|
|
|
}
|