[英]How to use long polling in native JavaScript and node.js?
我需要为聊天应用程序实现long polling
。 我四处搜索,但我只找到了如何使用JQuery
在JavaScript
实现它。 如何仅使用native JavaScript
和node.js
来实现它? 你能指导我一些相关的文章或材料吗?
问:如何在nodeJS
原生Javascript
中进行长轮询?
A:我想首先你需要了解长轮询模型是如何工作的。 如果您没有任何线索,那么RFC-6202 规范是一个很好的起点。
它是关于客户端向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://localhost:9999/
进行HTTP
调用。 您应该注意到,在前两个调用中您不会得到响应,并且当您触发第三个调用时,您将收到所有先前和当前调用的响应。
这里的想法是你首先存储请求的response
对象,当一个事件通过时,假设每 3 次 HTTP 调用,然后循环遍历所有响应并回复它们。 对于您的聊天应用程序,触发响应的事件可能是有人向聊天室发送消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.