Dra*_*cir 3 sockets https proxy node.js
如果我在 Node.JS 中创建一个简单的服务器
var httpServer = http.createServer(callback);
httpServer.on('connect', function(req, socket, head){
console.log('connect');
});
httpServer.listen(3128, '192.168.0.2');
Run Code Online (Sandbox Code Playgroud)
收到connect活动后应该怎么做?
背景
connect将触发该事件理想情况下,我想做的是将请求代理到终端服务器,然后给客户端响应。
但我在这里看不到任何 API。该connect回调不具备的普遍观点(request, response),而是接受(request, socket, head)。
我如何满足请求并发出响应?
从头重写的答案
这是一个简单的例子。
connect事件处理程序传递了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();
});
});
Run Code Online (Sandbox Code Playgroud)