文章目录
websocket
用于客户端与服务端双向通信的工具
使用
javascript
//node
const ws = require('ws');
const app = express();
app.use(cors());
const server = http.createServer(app);
const wss = new ws.Server({ server });
wss.on('connection', (ws) => {
//初始化
cilentInit(ws);
//事件处理
ws.on('message', (data) => {
solveMessage(ws, data);
});
//结束
ws.on('close', () => {
cilentLeave(ws);
});
});
//web建立连接
ws = new WebSocket(url)
//发送消息
ws.send(data)
原生websocket仅提供了较为简单的机制(如下)
typescript
// 1. 连接成功
ws.onopen = () => ws.send('hello')
// 2. 收到消息
ws.onmessage = (e) => console.log(e.data)
// 3. 异常
ws.onerror = (e) => console.error(e)
// 4. 关闭
ws.onclose = (e) => console.log('code=', e.code)
其中前半部分是事件,后面是执行的动作
ws.send主动向服务器发送数据
问题
- 原生api发送数据没有
timesetout与promise等,即发送数据后想要等待服务器消息的机制,与超时等需要自己实现 - 需要手动对发送的消息进行分类如使用
type参数
简单封装
- 实现异步机制
- 能够分发事件监听与随时去除
typescript
private pendingPromises = new Map<string, { resolve: Function; reject: Function }>()
waitForMessage(type: string, timeout = 10000): Promise<any> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingPromises.delete(type)
reject(new Error(`等待消息类型 "${type}" 超时`))
}, timeout)
this.pendingPromises.set(type, { resolve: (data) => { clearTimeout(timer); resolve(data) }, reject })
})
}