【发布时间】:2020-11-04 13:36:33
【问题描述】:
我想要一个 HTTP 服务器,只要我在浏览器的 URL 中指定给定路径,就可以与远程计算机建立 TCP 连接。
例如...假设我有一台具有公共 IP 地址和主机名作为服务器 (mydomain.com:9000) 的计算机和一台具有本地 IP 地址 (192.168.0.1) 的远程计算机连接到服务器。不知何故,我想在客户端和远程计算机之间建立 TCP 连接。为了更容易,只需输入带有路径的 URL (mydomain.com:9000/remote)。没有另一个端口!另外,我希望当且仅当输入该路径时才能完成连接。
为了更好地说明系统的工作原理:
_________ _________ _________
| | internet | | local network | |
|_______| ----------> |_______| ----------> |_______|
____|____ <---------- ____|____ <---------- ____|____
client server remote computer
sends http request checks path gets http request
mydomain.com:9000/remote establishes TCP connection handles request
我用 node js 编写了一些代码来确保连接是可能的。是的,现在我只需要能够检查路径并建立连接。我的代码是一个简单的 TCP 隧道代理,它工作正常。但是当我尝试实现路径时它没有。
//Import modules
const net = require('net');
const http = require('http');
let inpath = false;
// Create proxy server
const proxy = http.createServer( function(req,res){
console.log(req.url);
//Check path
if(req.url == '/remote')
inpath = true;
});
proxy.on('connection', client => {
if(inpath)
{
const remote = new net.Socket();
//Establish connection
remote.connect(80,'192.168.0.100');
client.on('error', err => {
console.log('Error: ' + err);
proxy.close();
});
//Port-forwarding
client.pipe(remote);
remote.pipe(client);
}
});
proxy.listen(9000);
有没有办法做到这一点?
【问题讨论】:
标签: javascript node.js http tcp