【发布时间】:2014-02-24 22:07:11
【问题描述】:
我希望我的 Node.js 代码向另一台服务器发送一个 http 请求。使用下面的代码可以正常工作。我的问题是有问题的服务器应该推送数据,并且连接在请求后立即关闭。
例如,如果我使用浏览器打开页面,我会从服务器获取推送数据,并且我的页面会被浏览器刷新。问题是:我怎样才能在我的 Node 服务器中获取跟随我的 http 请求的推送请求(来自其他服务器)? 我尝试使用“keep-alive”,但这不会改变任何东西。
示例代码:
var http = require("http");
var agent = new http.Agent;
var options = {
hostname: 'server.com',
port: 80,
path: '/',
method: 'GET',
agent: agent,
headers: {
'Connection':'keep-alive'
}
};
var req = http.request(options, function(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', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
【问题讨论】:
-
服务器推送是如何实现的?