Node.js 长轮询请求
Node.js long polling request
我正在尝试了解如何从我的 Node.js 应用中使用远程长轮询资源。我尝试使用 "request" 包,连接保持打开状态,但我无法读取来自远程资源的数据。
谁能告诉我该怎么做?
提前致谢。
终于找到解决方案:
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
- 代理保持活动状态
自定义修改:
每次服务器端点重新启动时,连接都会关闭套接字并且不会重新连接。为了解决这个问题,我修改了 node_modules/agentkeepalive/lib/agent.js 并添加了一个名为 resetStatus 的新值和一个新函数 setCurrentStatus,因此每次连接关闭时,计数都会重置为 0 并再次调用 makeRequest 函数。
感谢您的宝贵时间!
我正在尝试了解如何从我的 Node.js 应用中使用远程长轮询资源。我尝试使用 "request" 包,连接保持打开状态,但我无法读取来自远程资源的数据。
谁能告诉我该怎么做?
提前致谢。
终于找到解决方案:
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
- 代理保持活动状态
自定义修改: 每次服务器端点重新启动时,连接都会关闭套接字并且不会重新连接。为了解决这个问题,我修改了 node_modules/agentkeepalive/lib/agent.js 并添加了一个名为 resetStatus 的新值和一个新函数 setCurrentStatus,因此每次连接关闭时,计数都会重置为 0 并再次调用 makeRequest 函数。
感谢您的宝贵时间!