【发布时间】:2010-04-06 22:27:39
【问题描述】:
我有一个典型的服务器,一个朋友使用客户端连接到我的 IP/端口,他一直收到异常:“连接尝试失败,因为连接方在一段时间后没有正确响应,或已建立的连接失败,因为连接的主机未能响应 {MY_IP}:{MY_PORT}"—您不需要知道我的 IP。
但是,客户端和服务器在环回地址 (127.0.0.1) 上工作正常。我也没有任何防火墙,Windows 防火墙也没有激活。
服务器:
static void Main(string[] args)
{
Console.Title = "Socket Server";
Console.WriteLine("Listening for messages...");
Socket serverSock = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress serverIP = IPAddress.Any;
IPEndPoint serverEP = new IPEndPoint(serverIP, 33367);
SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "98.112.235.18", 33367);
serverSock.Bind(serverEP);
serverSock.Listen(10);
while (true)
{
Socket connection = serverSock.Accept();
Byte[] serverBuffer = new Byte[8];
String message = String.Empty;
while (connection.Available > 0)
{
int bytes = connection.Receive(
serverBuffer,
serverBuffer.Length,
0);
message += Encoding.UTF8.GetString(
serverBuffer,
0,
bytes);
}
Console.WriteLine(message);
connection.Close();
}
}
客户:
static void Main(string[] args)
{
// Design the client a bit
Console.Title = "Socket Client";
Console.Write("Enter the IP of the server: ");
IPAddress clientIP = IPAddress.Parse(Console.ReadLine());
String message = String.Empty;
while (true)
{
Console.Write("Enter the message to send: ");
// The messsage to send
message = Console.ReadLine();
IPEndPoint clientEP = new IPEndPoint(clientIP, 33367);
// Setup the socket
Socket clientSock = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// Attempt to establish a connection to the server
Console.Write("Establishing connection to the server... ");
try
{
clientSock.Connect(clientEP);
// Send the message
clientSock.Send(Encoding.UTF8.GetBytes(message));
clientSock.Shutdown(SocketShutdown.Both);
clientSock.Close();
Console.Write("Message sent successfully.\n\n");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
【问题讨论】:
-
服务器端有路由器吗?
-
你的朋友有防火墙吗?
-
我确实有一个路由器服务器端,我的朋友在防火墙后面。我现在会尝试测试这些。
-
确保路由器将必要的端口转发到您的计算机。
-
我转发了路由器中的端口,他关闭了防火墙,但我的朋友仍然无法连接——他收到了同样的错误。