为了学习目的,我开发了一个在本地网络上工作的异步服务器/客户端应用程序。但是现在我想让它能够连接到我的公共IP地址,所以我的服务器可以从任何地方访问。C#公共IP客户端/服务器
这里是服务器代码的相关部分,它似乎是工作得很好:
static void Main(string[] args)
{
AsyncServer server = new AsyncServer(60101);
server.RunAsync();
Console.Read();
}
public class AsyncServer
{
private IPAddress ipAddress;
private int port;
public AsyncServer(int port)
{
this.port = port;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
this.ipAddress = null;
for (int i = 0; i < ipHostInfo.AddressList.Length; i++)
{
if (ipHostInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
this.ipAddress = ipHostInfo.AddressList[i];
break;
}
}
if (this.ipAddress == null)
throw new Exception("No IPv4 address for server.");
}
public async void RunAsync()
{
TcpListener tcpListener = new TcpListener(this.ipAddress, this.port);
tcpListener.Start();
下面是客户端代码的相关部分。这是它无法连接的地方。
static void Main(string[] args)
{
AsyncClient client = new AsyncClient("MyPublicIP", 60101);
client.ConnectAsync().Wait();
Console.Read();
}
}
public class AsyncClient
{
private IPAddress ipAddress;
private int port;
public AsyncClient(string ip, int port)
{
this.port = port;
IPAddress.TryParse(ip, out ipAddress);
}
public async Task ConnectAsync()
{
int attempts = 0;
TcpClient client = new TcpClient();
while (!client.Connected)
{
try
{
attempts++;
client.Connect(this.ipAddress, this.port);
Console.Clear();
Console.WriteLine("Connected");
await ProcessAssync(client);
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Connection Attempts: {0}", attempts);
我已经在我的路由器上进行端口转发到我的本地服务器IP“192.168.254.1”所使用的端口“60101”,但没有什么变化,他只是不断尝试出现了一会儿,然后失败连接。
他不会被连接到192.168.254.1 ..他需要你的互联网IP地址,这就是当地的一个 – BugFinder
是,192.168.254.1是我的地方IP,但这是我需要的服务器的权利?因此,服务器会监听给定端口上发送给此IP的所有内容,就像我设置端口转发一样。然后在客户端上,我不试图连接到它,它试图连接到我的公共IP。这不是应该如何? –
是的,这听起来正确。所以问题可能是ISP过滤或转发不工作或其他事情。 –