我正在尝试使用C#创建一个服务器。目前,我有两个程序,一个服务器和一个客户端,当它们都在同一台计算机上运行时,它们都能正常工作,服务器的TcpListener
是使用ip 127.0.0.1(localhost)创建的,客户端连接到ip 127.0.0.1。然而,当我尝试使用我的公共ip连接到服务器时,客户端程序等待大约20秒,然后我得到一个SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
我已经转发了我正在使用的端口(端口是2345)。我在另一台电脑上尝试了与上面相同的步骤,但仍然得到了相同的结果。我在创建服务器的TcpListener
时尝试使用公共ip,但后来我得到了SocketException: The requested address is not valid in its context
,所以我认为我应该只使用127.0.0.1(不过我可能错了,这是我第一次尝试这样的东西)。
这是创建服务器的功能。
public static void RunServer()
{
string ipStr = "";
Console.WriteLine("Enter IP...");
ipStr = Console.ReadLine();
if (ipStr == "localhost")
ipStr = "127.0.0.1";
IPAddress ip = IPAddress.Parse(ipStr);
int port = -1;
Console.WriteLine("Enter port...");
while (port == -1)
{
try
{
port = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter an integer.");
}
}
Console.WriteLine("Starting server on " + ip + ":" + port);
TcpListener tcpListener;
try
{
tcpListener = new TcpListener(ip, port);
tcpListener.Start();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
Console.ReadLine();
return;
}
while (true)
{
try
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
string msg = sr.ReadToEnd();
Console.WriteLine("Received message: "" + msg + """);
sr.Close();
networkStream.Close();
tcpClient.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
以及创建客户端的功能。
public static void RunClient()
{
string ip = "";
Console.WriteLine("Enter IP...");
ip = Console.ReadLine();
int port = -1;
Console.WriteLine("Enter port...");
while (port == -1)
{
try
{
port = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter an integer.");
}
}
while (true)
{
Console.WriteLine("Enter message...");
string msg = Console.ReadLine();
Console.WriteLine("Sending message: "" + msg + """);
TcpClient tcpClient;
try
{
tcpClient = new TcpClient(ip, port);
}
catch (SocketException e)
{
Console.WriteLine("Could not connect to server. Connection refused.");
Console.WriteLine("Exception: " + e);
continue;
}
NetworkStream networkStream = tcpClient.GetStream();
networkStream.Write(Encoding.ASCII.GetBytes(msg), 0, msg.Length);
Console.WriteLine("Sent message!");
networkStream.Close();
tcpClient.Close();
}
}
我原以为我目前所拥有的一切都会奏效,但我得到的只是一个例外。
问题是服务器程序的IPAddress ip = IPAddress.Parse(ipStr);
行应该是IPAddress ip = IPAddress.Any;
这是因为计算机的防火墙正在阻止连接。在防火墙的入站规则中,为您正在使用的端口添加异常。