`
liue
  • 浏览: 19394 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

NodeJs http

 
阅读更多
This article is coming from: https://stackoverflow.com/questions/28229044/http-keep-alive-in-node-js


var http = require("http");

var agent = new http.Agent();
agent.maxSockets = 1;

var sockets = [];

function request(hostname, path, callback) {
    var options = {
        hostname: hostname,
        path: path,
        agent: agent,
        headers: {"Connection": "keep-alive"}
    };
    var req = http.get(options, function(res) {
        res.setEncoding('utf8');
        var body = "";
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            callback(null, res, body);
        });
    });
    req.on('error', function(e) {
        return callback(error);
    });
    req.on("socket", function (socket) {
        if (sockets.indexOf(socket) === -1) {
            console.log("new socket created");
            sockets.push(socket);
            socket.on("close", function() {
                console.log("socket has been closed");
            });
        }
    });
}

function run() {
    request('www.twilio.com', '/', function (error, res, body) {
        setTimeout(run, 1000);
    });
}

run();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics