首页 > 解决方案 > Nodejs API 使用 Promise 等待 websocket 事件

问题描述

我有一个 websocket 服务器,它将为所有发送的消息(事件)发送一个“确认”事件。

对我的 Nodejs 服务器的 HTTP API 请求会将“登录”事件发送到 ws 服务器并等待来自 ws 服务器的事件。

一旦从 ws 服务器接收到“确认”事件(对于发送的“登录”事件),API 需要发送响应。

整体流程: 在此处输入图像描述 如何让API等待ws事件??

示例代码:

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); 
});

标签: node.jsasynchronouswebsocketasync-awaitpromise

解决方案


推荐阅读