Node.js长轮询请求

Node.js长轮询请求,node.js,long-polling,Node.js,Long Polling,我试图了解如何使用Node.js应用程序中的远程长轮询资源。我尝试使用“请求”包,连接保持打开,但无法读取来自远程资源的数据 有人能告诉我怎么做吗 提前感谢。终于找到了解决方案: const https = require('https'); const Agent = require('agentkeepalive').HttpsAgent; const keepaliveAgent = new Agent({ maxSockets: 100, maxFreeSockets: 10,

我试图了解如何使用Node.js应用程序中的远程长轮询资源。我尝试使用“请求”包,连接保持打开,但无法读取来自远程资源的数据

有人能告诉我怎么做吗


提前感谢。

终于找到了解决方案:

const https = require('https');
const Agent = require('agentkeepalive').HttpsAgent;

const keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
});

const options = {
  host: 'server',
  port: port,
  auth: 'username:password',
  path: '/path',
  method: 'POST',
  agent: keepaliveAgent,
  headers: {
        'Accept': 'application/json'
  }
};

makeRequest();

function makeRequest(){
  const req = https.request(options, res => {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });
  req.on('error', e => {
    console.log('problem with request: ' + e.message);
    makeRequest();
  });
  req.end();

  }

setInterval(() => {
  if (keepaliveAgent.statusChanged) {
    if(keepaliveAgent.getCurrentStatus().resetStatus != 0){
            keepaliveAgent.setCurrentStatus();
            makeRequest();
    }
  }
}, 2000);
所需软件包:

  • https
  • 代理保留
自定义修改: 每次服务器端点重新启动时,连接都会关闭套接字,而不会重新连接。为了处理这个问题,我修改了节点_modules/agentkeepalive/lib/agent.js,并添加了一个名为resetStatus的新值和一个新函数setCurrentStatus,因此每次连接关闭时,计数都会重置为0,并再次调用makeRequest函数


谢谢你的时间

你能详细说明一下吗?也许分享一些你写的代码?是的!需要更多的澄清。您还可以在此处详细说明您试图使用的资源。