fite/lib/ws.js

47 lines
924 B
JavaScript

/**
* 一个简单到极致的 WebSocket 类
* @author yutent<yutent.io@gmail.com>
* @date 2023/01/17 17:32:51
*/
import { WebSocketServer } from 'ws'
function defer() {
var o = {}
o.promise = new Promise((resolve, reject) => {
o.resolve = resolve
o.reject = reject
})
return o
}
class WebSocket {
#ws = null // ws实例
#queue = [] // 消息队列
constructor(server) {
var 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)
}
})
}
send(msg = {}) {
if (this.#ws) {
this.#ws.send(JSON.stringify(msg))
} else {
this.#queue.push(msg)
}
}
}
export default function (server) {
return new WebSocket(server)
}
vue3的轻量构建工具。webpack/vite的替代品
JavaScript 100%