2010-02-28 2 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

+3

ex.Message의 표시를 중단 할 것을 권합니다. Ex.ToString()을 대신 사용하십시오. –

+1

@ezgar, 이전에 대답했지만 다른 문제를 다루기 때문에 코드를 테스트 한 후에 삭제했습니다. sniperX가 물었던 것처럼, 예외가 어디서 던져졌으며 예외 메시지는 무엇입니까? 내 설치 프로그램이 'dyndns.org'로 검색 할 공용 IP를 가지고 있지 않아 비슷한 오류를 복제 할 수 없습니다. –

답변

1

이드 대신 소켓 장난의, TcpListener 및하여 TcpClient 클래스로 보는 것이 좋습니다 ..하는 TCP *의 당신

+0

자, 확인해 보겠습니다. – ezgar

1

는 공용 IP를 얻기 위해 모든 물건을 할 클래스는 같은 (NAT 장치 뒤에있는 것을 의미한다 간단한 홈 라우터). 장치가 포트 5656에 대한 TCP 연결을 서버 시스템으로 전달하고 서버의 방화벽도 구성되었는지 확인 했습니까?

+0

네, 해냈습니다. – ezgar

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

1

여기 실패에 대한 충분한 공간이 있습니다. 수작업으로 입력하지 않으면 클라이언트가 서버의 IP 주소를 추측 할 수있는 가능성이 희박합니다. 다른 네트워크에서도 실행해야합니다. 동일한 컴퓨터에서이 주소를 테스트하는 경우 로컬 컴퓨터 두 대를 함께 사용하여이 주소를 테스트하는 경우 로컬 IP 주소 사용을 고려하십시오 (127.0.0.1). 포트 번호는 방화벽에 의해 거의 확실하게 차단됩니다. 당신은 그것에 대한 명시적인 예외를 만들어야 할 것이다.

+0

예, 서버의 IP 주소는 사용자가 텍스트 상자에 입력합니다. 방화벽을 사용하지 않도록 설정했습니다. – ezgar

+0

그래서 몇 대의 기계를 사용하고 네트워크는 어떻게 생겼으며 127.0.0.1을 시도 했습니까? 내 대답의 나머지도 중요합니다. –

관련 문제