SocketException';关联方在一段时间后未作出适当回应;使用公共ip(C#)连接到服务器时
我正在尝试使用C#创建服务器。目前,我有两个程序,一个服务器和一个客户端,当它们都在同一台计算机上运行时,它们都能正常工作,服务器的SocketException';关联方在一段时间后未作出适当回应;使用公共ip(C#)连接到服务器时,c#,network-programming,system.net,system.net.sockets,C#,Network Programming,System.net,System.net.sockets,我正在尝试使用C#创建服务器。目前,我有两个程序,一个服务器和一个客户端,当它们都在同一台计算机上运行时,它们都能正常工作,服务器的TcpListener是使用ip 127.0.0.1(本地主机)创建的,客户端连接到ip 127.0.0.1。但是,当我尝试使用我的公共ip连接到服务器时,客户端程序等待大约20秒,然后我得到一个SocketException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机没有响应 我已经转发了我正在使用的端口(端口是2345)
TcpListener
是使用ip 127.0.0.1(本地主机)创建的,客户端连接到ip 127.0.0.1。但是,当我尝试使用我的公共ip连接到服务器时,客户端程序等待大约20秒,然后我得到一个SocketException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机没有响应
我已经转发了我正在使用的端口(端口是2345)。我在另一台计算机上尝试了上述相同的步骤,但仍然得到了相同的结果。在创建服务器的TcpListener
时,我尝试使用公共ip,但随后我得到了SocketException:请求的地址在其上下文中无效
,因此我假设我应该只使用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)服务器程序的code>应该是IPAddress ip=IPAddress.Any代码>我尝试为端口和程序添加规则,但都不起作用。另外,如果有必要的话,我使用的端口是2345。完美的答案,节省了我的时间!