我有一个从外部API监听webhook事件的Express服务器。当它接收到这些事件时,我希望该http请求的处理程序向WebSocket客户端发送一条消息。下面是一些基本代码来说明我的意思
外部API将发送一个HTTP POST请求到我的Express服务器上的一个端点,假设它如下所示:
app.post('/external-api', (req, res) => {
// webhook payload will be in req.body
})在/external-api处理程序中,我想向通过WebSocket连接到服务器的客户机发送一条消息。到目前为止,我使用的是npm ws库,所以我希望逻辑看起来像这样
app.post('/external-api', (req, res) => {
ws.broadcast(req.body);
})有没有办法做到这一点?我对使用其他库持开放态度,但我只需要一种从Express中的HTTP POST请求处理程序向WebSocket客户机发送消息的方法。
发布于 2020-07-27 17:53:39
下面是一个示例:
index.ts
import express from 'express';
import WebSocket from 'ws';
import http from 'http';
import path from 'path';
import faker from 'faker';
const app = express();
const port = 3000;
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws: WebSocket) => {
console.log('establish websocket connection');
ws.on('message', (message) => {
console.log('received: %s', message);
});
});
app.get('/client/:id', (req, res) => {
res.sendFile(path.resolve(__dirname, `./public/client-${req.params.id}.html`));
});
app.get('/external-api', (req, res) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(faker.internet.email());
}
});
res.sendStatus(200);
});
server.listen(port, () => console.log(`http server is listening on http://localhost:${port}`));client-1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client 1</title>
</head>
<body>
<p>client 1</p>
<button id="test">Test</button>
<script>
(function() {
window.onload = function() {
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function(event) {
socket.send('Hello Server! Client - 1');
});
// Listen for messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event.data);
});
const btn = document.getElementById('test');
btn.addEventListener('click', async () => {
try {
const res = await fetch('http://localhost:3000/external-api');
console.log(res);
} catch (error) {
console.log(error);
}
});
};
})();
</script>
</body>
</html>client-2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client 2</title>
</head>
<body>
<p>client 2</p>
<button id="test">Test</button>
<script>
(function() {
window.onload = function() {
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function(event) {
socket.send('Hello Server! Client - 2');
});
// Listen for messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event.data);
});
const btn = document.getElementById('test');
btn.addEventListener('click', async () => {
try {
const res = await fetch('http://localhost:3000/external-api');
console.log(res);
} catch (error) {
console.log(error);
}
});
};
})();
</script>
</body>
</html>现在,单击client 1的按钮,将HTTP请求发送到/external-api。
客户端1的控制台日志:

客户端2的控制台日志:

服务器的日志:
http server is listening on http://localhost:3000
establish websocket connection
received: Hello Server! Client - 1
establish websocket connection
received: Hello Server! Client - 2如您所见,服务器向客户端1和客户端2广播假电子邮件。
https://stackoverflow.com/questions/63099518
复制相似问题