If I create a simple server in Node.JS
var httpServer = http.createServer(callback);
httpServer.on('connect', function(req, socket, head){
console.log('connect');
});
httpServer.listen(3128, '192.168.0.2');
What should I do when I receive the connect
event?
Background
connect
event is firedIdeally what I would like to do is, proxy the request to the end server, and then give the client the response.
But I can't see any API for doing that here. The connect
callback doesn't have the usual arguments of (request, response)
, instead it accepts (request, socket, head)
.
How do I fulfil the request and issue a response?
Answer rewritten from scratch
Here is simple example.
connect
event handler have passed socket
object which we have to tie with remote connection's socket.
httpServer.on('connect', function(req, socket, head) {
var addr = req.url.split(':');
//creating TCP connection to remote server
var conn = net.connect(addr[1] || 443, addr[0], function() {
// tell the client that the connection is established
socket.write('HTTP/' + req.httpVersion + ' 200 OK\r\n\r\n', 'UTF-8', function() {
// creating pipes in both ends
conn.pipe(socket);
socket.pipe(conn);
});
});
conn.on('error', function(e) {
console.log("Server connection error: " + e);
socket.end();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With