DomQ
DomQ

Reputation: 4664

How to do HTTP over an already created socket?

I have some networking code that creates sockets, and I would like to do HTTP on them using Node's standard HTTP API.

Starting like this,

var http = require('http'),
    net = require('net');

var port = 12345;
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end("Hello world");
}).listen(port);

var sock = net.createConnection({port: port});

How do I pass sock into http.get() or similar?

Upvotes: 1

Views: 80

Answers (1)

DomQ
DomQ

Reputation: 4664

This can be done with a custom http.Agent:

var agent = new http.Agent({ maxSockets: 1 });
agent.createSocket = function() {return sock};
http.get({
    host: "localhost",
    port: port,
    path: "/",
    agent: agent}, function(res) {
        // ...
    });

Upvotes: 1

Related Questions