Skip to content

Instantly share code, notes, and snippets.

@fr6nco
Last active March 12, 2018 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fr6nco/3435160d3979017c06ce41c4d2c2f58d to your computer and use it in GitHub Desktop.
Save fr6nco/3435160d3979017c06ce41c4d2c2f58d to your computer and use it in GitHub Desktop.
reuse nodejs socket for HTTP request
const net = require('net');
const http = require('http');
let client = new net.Socket();
let httpAgent = new http.Agent({keepAlive: true});
let sock = httpAgent.createConnection({port: 80, host:'localhost'}, (err, sock) => {
if(err) {
console.error(err);
}
});
sock.on('connect', () => {
console.log('socket connected');
let options = {
host: 'localhost',
port: 80,
path: '/',
method: 'GET',
createConnection: function() {
return sock;
}
};
console.log(options);
let req = http.request(options, (res) => {
res.on('data', (data) => {
console.log('And here is the result');
console.log(data.toString('utf8'));
});
res.on('error', (err) => {
console.error(err);
});
});
setTimeout(function () {
console.log('Just slept for 3 seconds');
console.log('Now lets send the request');
req.end();
}, 3000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment