Last active
March 12, 2018 21:13
-
-
Save fr6nco/3435160d3979017c06ce41c4d2c2f58d to your computer and use it in GitHub Desktop.
reuse nodejs socket for HTTP request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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