我正在尝试创建工具来模拟慢速网络服务器的场景。
X
Y
和 Z
。 example.com/api/X/
example.com/api/Y
等等。X
需要长达 50 秒的时间来响应 HTTP 请求。Y
和 Z
的服务器运行状况良好,前端甚至无法连接服务器 Y
和 Z
。我们的预感是,由于 HTTP 1.1 限制,对
X
的 5 次调用(2 次 HTTP 和 3 次 Websocket 连接尝试)通过让其他 HTTP 调用和对其他后端服务器的 Websocket 连接尝试处于饥饿状态,从而占用了我们的前端应用程序 Y
和 Z
.
为了进行相同的测试,我们想要创建一个模拟服务器来延迟 HTTP 请求以及 Websocket 请求 - 特别是应该延迟 websocket 连接部分来模拟这种情况。
我尝试了以下方法,它在延迟 HTTP 调用方面效果很好,但是 websocket 连接立即连接,只是响应数据包被延迟,这不是我们想要的。
如何延迟websocket连接过程?
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// HTTP route
app.get('/', (req, res) => {
// Simulate a 50-second delay
setTimeout(() => {
res.send('HTTP Response: 200 OK');
}, 5000);
});
// WebSocket route
wss.on('connection', (ws) => {
ws.on('message', (message) => {
// Handle WebSocket messages
console.log(`Received: ${message}`);
setTimeout(() => {
ws.send(`Received: ${message}`);
}, 5000);
});
});
// Start the combined server
server.listen(8080, () => {
console.log('Combined HTTP and WebSocket server running on port 8080');
});
我使用
server.on('upgrade', cb)
基本上设置延迟,然后调用wss.handleUpgrade
。这样我就成功地在 websocket 初始化部分创建了延迟。
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ noServer: true });
const MOCK_DELAY_IN_MS = 50 * 1000;
// Middleware to introduce a 5-second delay for all HTTP GET requests
app.use((req, res, next) => {
if (req.method === 'GET') {
setTimeout(next, MOCK_DELAY_IN_MS);
} else {
next();
}
});
// Route to handle all GET requests
app.get('*', (req, res) => {
res.status(200).send('OK');
});
server.on('upgrade', (request, socket, head) => {
// Delay WebSocket connection for 5 seconds
setTimeout(() => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
}, MOCK_DELAY_IN_MS);
});
wss.on('connection', (ws) => {
console.log('WebSocket connection established.');
ws.on('message', (data) => {
ws.send(`Received: ${data}`);
});
// Handle the WebSocket connection here
});
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});