Skip to content

Instantly share code, notes, and snippets.

@Lukewh
Created October 16, 2012 10:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lukewh/3898463 to your computer and use it in GitHub Desktop.
Save Lukewh/3898463 to your computer and use it in GitHub Desktop.
Node.js sockets
// Create the http handler
var http = require('http');
// Set the http protocol to have 10 sockets
http.globalAgent.maxSockets = 10;
// Create the http and https handlers
var http = require('http'),
https = require('https');
// Set the http protocol to have 10 sockets
http.globalAgent.maxSockets = 10;
// Set the https protocol to have 12 sockets
https.globalAgent.maxSockets = 12;
// http.globalAgent
{ options: {},
requests: {
'host': [
array of client requests (http://nodejs.org/api/http.html#http_class_http_clientrequest)
]
},
sockets: {
'host': [
array of net sockets (http://nodejs.org/api/net.html#net_class_net_socket)
]
},
maxSockets: 5, // Global maximum
_events: { free: [Function] },
createConnection: [Function]
}
// Create the http and http2 handler
var http = require('http'),
http2 = require('http');
// Set the main global agent
http.globalAgent.maxSockets = 25;
// Set the instance of http to have 10 sockets
http.Agent.maxSockets = 10;
// Set the instance of http2 to have 15 sockets
http2.Agent.maxSockets = 15;
// Some socket helpers
var sockets = {
// How many are in use altogether
inUse: function(http){
// Set default to 0
var httpPool = 0;
var socketList = http.globalAgent.sockets;
// For each socket
for(var socket in socketList){
if(socketList.hasOwnProperty(socket)){
// Add the number of sockets
httpPool += socketList[socket].length;
/*
* Note that each item in socketList[socket] is an instance
* of a net socket (http://nodejs.org/api/net.html#net_class_net_socket)
*/
}
}
return httpPool;
},
// Which hosts are we connected to
hosts: function(http){
var hosts = [];
var socketList = http.globalAgent.sockets;
for(var socket in socketList){
if(socketList.hasOwnProperty(socket)){
hosts.push(socket);
}
}
return hosts;
}
};
// Usage
// Log the number of connections in use
console.log(socket.inUse(http));
// Hosts connected to
console.log(sockets.hosts(http));
// Create the http and http2 handler
var http = require('http'),
http2 = require('http');
// Set the instance of http to have 10 sockets
http.globalAgent.maxSockets = 10;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment