2010-02-28 125 views
1

我无法连接简单的客户端和简单的服务器。当我运行服务器时,似乎没有任何问题,但是当我尝试向客户端发送数据时,它会引发异常,说它在超时期限内未连接。.NET中的套接字无法连接

这里是我使用的服务器代码:

public void server() 
    { 
     try 
     { 
      byte[] bytes = new byte[1024]; 
      int bytesReceived = 0; 
      String message = ""; 
      IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs 
      IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
      Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      socketServer.Bind(directionPort); 
      socketServer.Listen(100); 
      while (true) 
      { 
       Socket client = socketServer.Accept(); 
       bytesReceived = client.Receive(bytes); 
       message = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesReceived); 

       editMultiline.Invoke(new writeMessageDelegate(writeMessage), new object[] { message, "client"}); //Ignore this, it is just to show the info in a textbox because the server code runs in a diferent thread 

       client.Shutdown(SocketShutdown.Both); 
       client.Close(); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

这样,我从机器中获得的公网IP在其上运行程序:

public string getIPExternal() 
    { 
     string direction; 
     WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); 
     WebResponse response = request.GetResponse(); 
     StreamReader stream = new StreamReader(response.GetResponseStream()); 
     direction = stream.ReadToEnd(); 
     stream.Close(); 
     response.Close(); 

     //Search for the ip in the html 
     int first = direction.IndexOf("Address: ") + 9; 
     int last = direction.LastIndexOf("</body>"); 
     direction = direction.Substring(first, last - first); 

     return direction; 
    } 

这里是我的客户端代码:

public void client(string directionIP, string message) //directionIP is the IP from the computer to which i want to get connected 
    { 
     try 
     { 
      byte[] bytesSend = System.Text.Encoding.Unicode.GetBytes(message); 
      IPAddress direction = IPAddress.Parse(directionIP); 
      IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
      Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      socketClient.Connect(directionPort); 
      socketClient.Send(bytesSend); 
      socketClient.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

任何建议都会很棒。

+1

究竟在哪里抛出异常? – caesay 2010-02-28 03:26:44

+3

我催促你停止显示ex.Message。改用ex.ToString()。 – 2010-02-28 03:29:34

+1

@ezgar,我早些时候回答过,但在测试代码后删除了它,因为它解决了不同的问题。正如sniperX所问,抛出的异常究竟在哪里以及异常信息是什么?我无法复制类似的错误,因为我的设置没有公开的IP,我可以通过'dyndns.org'进行检索。 – 2010-02-28 04:56:05

回答

1

编号建议寻找到的TcpListener和TcpClient的类,而不是用插座玩弄..在TCP *类的做所有的东西你

+0

好的,我会检查出来。 – ezgar 2010-02-28 23:01:56

1

获取公网IP意味着你是一个NAT设备后面(如一个简单的家庭路由器)。您确定设备正在将TCP连接转发到端口5656到服务器计算机,并且服务器的防火墙也已配置好吗?

+0

是的,我已经完成了。 – ezgar 2010-02-28 23:01:29

1

请尝试此代码。也许没有资源泄漏,这将更好地工作:

public void server() 
{ 
    try 
    { 
     byte[] bytes = new byte[1024]; 
     IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs 
     IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
     using (Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) 
     { 
      socketServer.Bind(directionPort); 
      socketServer.Listen(100); 
      while (true) 
      { 
       using (Socket client = socketServer.Accept()) 
       { 
        int bytesReceived = client.Receive(bytes); 
        String message = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesReceived); 

        editMultiline.Invoke(new writeMessageDelegate(writeMessage), new object[] { message, "client" }); //Ignore this, it is just to show the info in a textbox because the server code runs in a diferent thread 

        client.Shutdown(SocketShutdown.Both); 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString(), "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 

public string getIPExternal() 
{ 
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); 
    string direction; 
    using (WebResponse response = request.GetResponse()) 
    { 
     using (Stream responseStream = response.GetResponseStream()) 
     { 
      using (StreamReader reader = new StreamReader(responseStream)) 
      { 
       direction = reader.ReadToEnd(); 
      } 
     } 
    } 

    //Search for the ip in the html 
    int first = direction.IndexOf("Address: ") + 9; 
    int last = direction.LastIndexOf("</body>"); 
    return direction.Substring(first, last - first); 
} 

ABD客户端:

public void client(string directionIP, string message) //directionIP is the IP from the computer to which i want to get connected 
{ 
    try 
    { 
     byte[] bytesSend = System.Text.Encoding.Unicode.GetBytes(message); 
     IPAddress direction = IPAddress.Parse(directionIP); 
     IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
     using (Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) 
     { 
      socketClient.Connect(directionPort); 
      socketClient.Send(bytesSend); 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString(), "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 
+0

好吧,我会检查你的代码;谢谢。 – ezgar 2010-02-28 23:02:29

1

有足够的空间为失败在这里。客户端能够猜出服务器的IP地址的几率很小,除非您亲自输入。它也必须在另一个网络上运行。考虑使用本地IP地址,如果您使用两台机器进行测试,如果您在同一台机器上测试,请使用127.0.0.1。端口号几乎肯定会被防火墙阻止。你必须为它做一个明确的例外。

+0

是的,来自服务器的IP地址是由用户在文本框中引入的;我已禁用防火墙。 – ezgar 2010-02-28 23:00:54

+0

因此,您使用多少台机器,网络是什么样的,您是否尝试过127.0.0.1?我的答案的其余部分也很重要。 – 2010-03-01 00:50:40