问:如何在原生Javascript in nodeJS 中进行长轮询?
答:我想首先您需要了解长轮询模型的工作原理。如果您还没有任何线索,那么RFC-6202 specification 是一个很好的起点。
这是关于客户端向server 发送request 并等待直到返回响应。
从规范中我们知道,首先客户端必须发出一个http 请求,该请求具有无限或至少一个高超时值。然后服务器,也就是你的nodeJs 应用程序,应该将所有传入的请求存储到一个数据结构中,基本上是一个保存区域。您的应用程序基本上会保留所有 response 对象,直到触发事件,然后您适当地回复响应。
考虑这个伪代码:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var requestCounter = 0;
var responses = {
/* Keyed by room Id =*/
"room_abc" : [ /* array of responses */]
};
app.get('/', function (req, res) {
requestCounter += 1;
var room = /* assuming request is for room_abc */ "room_abc";
// Stash the response and reply later when an event comes through
responses[room].push(res);
// Every 3rd request, assume there is an event for the chat room, room_abc.
// Reply to all of the response object for room abc.
if (requestCounter % 3 === 0) {
responses["room_abc"].forEach((res) => {
res.send("room member 123 says: hi there!");
res.end();
});
}
});
app.use(bodyParser.text({ type: 'text/*' }));
app.use(bodyParser.json());
app.listen(9999, function () {
console.log('Example app listening on port 9999!')
})
在这里编写一个工作示例相对耗时,但上面的代码是一个很好的示例,说明了如何在NodeJS 中实现长轮询。
如果您安装了postman 或curl,您可以使用GET 方法对HTTP 进行HTTP 调用。您应该注意到,在前两个调用中您不会得到响应,而当您触发第三个调用时,您将收到所有先前和当前调用的响应。
这里的想法是您首先存储请求的response 对象,当事件发生时,假设在每 3 次 HTTP 调用中,您然后循环所有响应并回复它们。对于您的聊天应用程序而言,触发响应的事件可能是有人向聊天室发送消息。