node.js - Nodejs API 使用 Promise 等待 websocket 事件
问题描述
我有一个 websocket 服务器,它将为所有发送的消息(事件)发送一个“确认”事件。
对我的 Nodejs 服务器的 HTTP API 请求会将“登录”事件发送到 ws 服务器并等待来自 ws 服务器的事件。
一旦从 ws 服务器接收到“确认”事件(对于发送的“登录”事件),API 需要发送响应。
示例代码:
const express = require('express')
const app = express()
const port = 3000
app.get('/login', (req, res) => {
ws.send({'id': 1234, 'type':'login', 'data': {'key':'value'}});
// wait for ack event from ws server
// verify the data received - ws.on('message', function incoming(data) { });
// send response if (data.type == 'login' && data.id == '1234') else timeout
res.send('success');
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
const WebSocket = require('ws');
const ws = new WebSocket('wss://echo.websocket.org/', {
origin: 'https://websocket.org'
});
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now());
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function incoming(data) {
console.log('event received');
console.log(data);
});
解决方案
推荐阅读
- c - 在 C 中打印字符串时如何解决此问题?
- android - 为什么用户详细信息会从 Firestore 中消失?
- bash - 如何使用户成为唯一能够访问文件的用户
- c# - 如果实例表示泛型参数,Type.Namespace 何时返回 null
- python-3.x - 如何在没有密码的情况下在 Linux 上运行脚本?
- github - GitHub Actions - *一些*空的环境秘密
- applescript - 是否有一种优雅的内置方式来处理别名?
- ios - 视觉人脸检测请求执行失败
- javascript - 如何更改 javascript 画布 DPI
- flutter - Flutter Google Maps 中对象的 FOV