问题
Im writing some integration tests for a node project.
We need to get reliable metrics about server performance. For that, we want to open a socket between the server and the client before any test is performance, this way, we can eliminate the time needed to create a socket between client and server.
I have created a small test case like this:
'use strict';
var express = require( 'express' ),
net = require('net'),
http = require('http');
var host = 'localhost',
port = 8000;
describe( 'dummy describe', function() {
var app, server, agent, opts;
before( function( done ) {
app = express();
app.get( '/', function( req, res, next ) {
res.send( 'stuff' );
});
server = http.createServer( app );
server.listen( 8000 );
agent = new http.Agent({ maxSockets: 1 });
agent.createConnection({ port: port, host: host }, function() {
return net.createConnection({ port: port, host: host }, function() {
console.log( 'Socket fd open on before block: ' + this._handle.fd );
done();
});
});
opts = {
hostname: host,
port: port,
path: '/',
agent: agent,
method: 'GET',
};
});
it( 'dummy test', function ( done ) {
var req = http.request( opts, function( res ) {
console.log( 'Socket fd used on GET: ' + res.socket._handle.fd );
done();
});
req.end();
});
});
Here, I can see the execution of the before block, where I console.log the socket file descriptor.
Reading node documentation, I figured out that his was the right way to pass a socket to a agent. But its not working, its output different sockets.
I tried a thousands combinations, but got no luck.
I want to manually connect to a socket, and then use it to perform http.request without having to re open a different socket.
What would be the correct way of doing this ?
来源:https://stackoverflow.com/questions/37328024/how-to-manually-open-socket-and-use-it-with-http-request