如何在原生 JavaScript 和 node.js 中使用长轮询?

How to use long polling in native JavaScript and node.js?

我需要为聊天应用程序实施 long polling。我四处搜索,但我只找到了如何使用 JQueryJavaScript 中实现它。如何仅使用 native JavaScriptnode.js 来实现它?能指导我看一些相关的文章或资料吗?

问: 如何在 nodeJS 中的原生 Javascript 中进行长轮询?

A: 我想您首先需要了解长轮询模型的工作原理。如果您没有任何线索,那么 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.

中实现长轮询

如果您安装了 postmancurl,您可以使用方法 GEThttp://localhost:9999/ 进行 HTTP 调用。您应该注意到,在前两次调用中您不会得到响应,而当您触发第三次调用时,您将收到所有之前和当前调用的响应。

这里的想法是首先存储请求的 response 对象,当事件发生时,假设在每 3 次 HTTP 调用时,您然后循环遍历所有响应并回复它们。对于您的聊天应用程序,触发响应的事件可能是有人向聊天室发送消息。