编辑:意识到我需要在C#上实现这个: https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT
我会尝试找一个,如果有人有,我会很感激,谢谢!
我可能刚刚在现场制作了这个名字。
我想要做的是拥有一台位于NAT后面的计算机,并且需要提供连接到服务器的服务。 然后,我将使用第三台计算机连接到该服务器,并与第一台计算机发起的TCP流进行交互,其工作方式就像我直接连接到它一样。
找到一种创建转发代理的方法,效果很好: blog.brunogarcia.com/2012/10/simple-tcp-forwarder-in-c.html
using System;
using System.Net;
using System.Net.Sockets;
namespace TcpProxy
{
class Program
{
static void Main(string[] args)
{
new TcpForwarderSlim().Start(
new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("69")),
new IPEndPoint(IPAddress.Parse("91.198.174.192"), int.Parse("80")));
}
}
public class TcpForwarderSlim
{
private readonly Socket _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void Start(IPEndPoint local, IPEndPoint remote)
{
_mainSocket.Bind(local);
_mainSocket.Listen(10);
while (true)
{
var source = _mainSocket.Accept();
var destination = new TcpForwarderSlim();
var state = new State(source, destination._mainSocket);
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
private void Connect(EndPoint remoteEndpoint, Socket destination)
{
var state = new State(_mainSocket, destination);
_mainSocket.Connect(remoteEndpoint);
_mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}
private static void OnDataReceive(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var bytesRead = state.SourceSocket.EndReceive(result);
if (bytesRead > 0)
{
state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None);
state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
catch
{
state.DestinationSocket.Close();
state.SourceSocket.Close();
}
}
private class State
{
public Socket SourceSocket { get; private set; }
public Socket DestinationSocket { get; private set; }
public byte[] Buffer { get; private set; }
public State(Socket source, Socket destination)
{
SourceSocket = source;
DestinationSocket = destination;
Buffer = new byte[8192];
}
}
}
}
有人能指出我正确的方向吗?
答案 0 :(得分:0)
UPNP可以在正确配置的路由器上打开端口。
当端口无法打开时,STUN,ICE和TURN使用中间服务器进行连接。有开源server implementations。
UDP可以使用UDP Hole Punching。
This answer提供了更详细的解释,但没有多少C#帮助。