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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45853418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:17:56  来源:igfitidea点击:

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

javascriptnode.jslong-polling

提问by user8244016

I need to implement long pollingfor a chat application. I've searched around, but I only find how to implement it in JavaScriptusing JQuery. How can I implement it using only native JavaScriptand node.js? Can you guide me to some relevant articles or materials?

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

回答by Samuel Toh

Q:How to do long polling in native Javascriptin nodeJS?

问:如何做长轮询在本机JavascriptnodeJS

A:I guess first of all you need to understand how the long polling model works. If you haven't had any clue then the RFC-6202 specificationis a good starting point.

A:我想首先你需要了解长轮询模型是如何工作的。如果您没有任何线索,那么RFC-6202 规范是一个很好的起点。

It is about the client sending a requestto the serverand waits until a response is returned.

它是关于客户端发送requestserver并等待返回响应。

From the specification we know that first the client will have to issue a httprequest which has an infinite or at least a high timeout value. Then the server, which is your nodeJsapplication is expected to stash all incoming requests into a data structure, basically a holding area. Your application will essentially hold on all the responseobject until an event gets triggered, then you reply to the responses appropriately.

从规范中我们知道,首先客户端必须发出一个http具有无限或至少高超时值的请求。然后服务器,也就是你的nodeJs应用程序,应该将所有传入的请求存储到一个数据结构中,基本上是一个保存区域。您的应用程序基本上将保留所有response对象,直到事件被触发,然后您适当地回复响应。

Consider this Pseudo code:

考虑这个伪代码:

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!')
})

It is relatively time consuming to write a working example here but the code above is a good example of how you can implement long polling in NodeJS.

在这里编写一个工作示例相对耗时,但上面的代码是一个很好的示例,说明如何在NodeJS.

If you have postmaninstalled or curlyou can do HTTPcalls to http://localhost:9999/using method GET. You should noticed that on the first two calls you won't get a response and it is when you fired the 3rd one then you'll receive a response for all previous and current calls.

如果您已经postman安装或者curl您可以HTTP调用http://localhost:9999/using 方法GET。您应该注意到,在前两个调用中您不会得到响应,并且当您触发第三个调用时,您将收到所有先前和当前调用的响应。

The idea here is you stash the request's responseobject first and when an event comes through, assuming on every 3rd HTTP call, you then loop through all of the responses and reply to them. For your chat application's case, the event that triggers a response would probably be when someone fires off a message to a chat room.

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