2014-02-10 7 views
4

node.js에서 두 개의 NAT를 통해 TCP 구멍을 펀치하려고합니다. 문제는 연결에 사용할 로컬 포트를 선택하는 방법을 알아낼 수 없다는 것입니다.Node.js의 TCP 구멍 펀칭

+0

가 발견 이 특정 문제에 대해 작동하는 해결 방법. 답변 게시. –

답변

1

소켓에 로컬 포트가 할당되었습니다. 동일한 포트를 다시 사용하려면 서버와 통신하는 데 사용 된 소켓과 동일한 소켓을 사용하여 클라이언트에 연결할 수 있습니다. 이것은 TCP 홀 펀칭을하고 있기 때문에 효과가 있습니다. 그러나 직접 포트를 선택할 수는 없습니다.

// server.js 
require('net').createServer(function(c) { 
    c.write(c.remotePort.toString(10)); 
}).listen(4434); 


//client.js 
var c = require('net').createConnection({host : '127.0.0.1', port : 4434}); 
c.on('data', function(data) { 
    console.log(data.toString(), c.localPort); 
    c.end(); 
}); 

c.on('end', function() { 
    c.connect({host : '127.0.0.1', port : 4434}); 
}); 
-1

대중 서버와의 연결을 생성 한 후, 당신은 또한 그 연결을 설정하는 데 사용 된 동일한 로컬 (!) 포트에서 수신 대기해야합니다 여기

는 몇 가지 테스트 코드입니다.

나는 개념의 완전한 TCP 홀 펀칭 증거에 testcode 확장 : 서버에서 발생하는 신호와 더 완전한 버전에 대한

// server.js 
var server = require('net').createServer(function (socket) { 
    console.log('> Connect to this public endpoint with clientB:', socket.remoteAddress + ':' + socket.remotePort); 
}).listen(4434, function (err) { 
    if(err) return console.log(err); 
    console.log('> (server) listening on:', server.address().address + ':' + server.address().port) 
}); 

// clientA.js 
var c = require('net').createConnection({host : 'PUBLIC_IP_OF_SERVER', port : 4434}, function() { 
    console.log('> connected to public server via local endpoint:', c.localAddress + ':' + c.localPort); 

    // do not end the connection, keep it open to the public server 
    // and start a tcp server listening on the ip/port used to connected to server.js 
    var server = require('net').createServer(function (socket) { 
     console.log('> (clientA) someone connected, it\s:', socket.remoteAddress, socket.remotePort); 
     socket.write("Hello there NAT traversal man, this is a message from a client behind a NAT!"); 
    }).listen(c.localPort, c.localAddress, function (err) { 
     if(err) return console.log(err); 
     console.log('> (clientA) listening on:', c.localAddress + ':' + c.localPort); 
    }); 
}); 

// clientB.js 
// read the server's output to find the public endpoint of A: 
var c = require('net').createConnection({host : 'PUBLIC_IP_OF_CLIENT_A', port : PUBLIC_PORT_OF_CLIENT_A},function() { 
    console.log('> (clientB) connected to clientA!'); 

    c.on('data', function (data) { 
     console.log(data.toString()); 
    }); 
}); 

, 내가 여기에 내 코드를 참조하십시오 https://github.com/SamDecrock/node-tcp-hole-punching

관련 문제