为什么我的服务器TcpListener使用本地地址而不使用公共地址?-异常:请求的地址在其上下文中无效



我使用TcpListener和TcpClient在C#中编写了一个服务器和一个客户端程序,我希望它们交换一个字符串。如果两台电脑都连接到同一个网络,并且我使用服务器的本地地址,它会工作,但当电脑连接到不同的网络,并且使用公共地址时,它会给我以下错误:

Exception: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at Server___Network_Class.Program.Main(String[] args) in D:Server - Network ClassProgram.cs:line 18

此错误指向第18行,即myList.Start((;但我不知道它为什么抛出这个异常。我打开了路由器端口,并正确设置了Windows防火墙。。。这是我写的服务器和客户端代码:

服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server___Network_Class {
class Program {
static void Main(string[] args) {
try {
IPAddress ipAddress = IPAddress.Parse("146.241.31.193"); //That's the public IP
//Initialize the listener
TcpListener myList = new TcpListener(ipAddress, 51328);
//Start listening the selected port
myList.Start();

Socket socket = myList.AcceptSocket();

ASCIIEncoding asen = new ASCIIEncoding();
socket.Send(asen.GetBytes("Can you read this?"));

socket.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}

客户端

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client___Class_Network {
class Program {
static void Main(string[] args) {
try {
//Inizializzo il client
TcpClient client = new TcpClient();
//Cerco di connettermi al server
client.Connect("146.241.31.193", 51328); //IP and Port i want to connect to

//Stream sul quale inviare e ricevere i dati dal server
NetworkStream stream = client.GetStream();
Byte[] bytesRecived = new Byte[256];
int totBytesRecived = stream.Read(bytesRecived, 0, bytesRecived.Length);
String stringData = System.Text.Encoding.ASCII.GetString(bytesRecived, 0, totBytesRecived);

Console.Write(stringData);
client.Close();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}

只有服务器程序抛出该异常,客户端程序似乎正在工作文件。。。

你能帮我解决这个问题吗?我(几乎(在网上找遍了,但找不到任何有用的答案。提前感谢!

公共IP地址在您的Windows机器上真的可用吗?还是只在路由器上可用?

在命令行窗口中运行ipconfig时,检查公共地址是否显示。我的猜测是,你需要在路由器中设置NAT端口转发,并设置应用程序来监听路由器给你的Windows机器的IP地址。这样的IP地址通常以CCD_ 2或CCD_。

尝试将服务器绑定到地址0.0.0.0。这样,它将在不需要任何配置的情况下监听您的所有网卡(WiFi、以太网(。

最新更新