2014-06-15 4 views
1
나는하여 TcpClient 클래스를 사용하여 원격 컴퓨터에 연결하기 위해 노력하고있어

에 연결하지,하지만 실패 유지 :하여 TcpClient는 원격 서버

'System.Net.Sockets.SocketException' 유형의 처리되지 않은 예외 System.dll을

에서 발생

추가 정보 : 연결된 호스트가 응답하지 않았기 때문에 연결된 파티 일정 시간 후에 제대로 응답하지 않았거나 설정된 연결이 실패했기 때문에 연결 시도가 실패

클라이언트와 서버가 로컬 작업 일 때 코드를 테스트하지만 원격 시스템에 연결하려고 시도하면 더 이상 작동하지 않습니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace WebSocketClient 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Opening up a TcpClient."); 
      TcpClient client = new TcpClient(); 
      client.Connect("<Remote Hostname>", <RemotePortNumber>); 
      Console.WriteLine("TcpClient has connected."); 
      NetworkStream stream = client.GetStream(); 
      bool closed = false; 
      new Thread(() => 
      { 
       while (!closed) 
       { 
        Console.WriteLine("Writing data to the stream."); 
        byte[] bytes = Encoding.UTF8.GetBytes("Hello, world."); 
        stream.Write(bytes, 0, bytes.Length); 
        Thread.Sleep(1000); 
       } 
      }).Start(); 
      Console.ReadLine(); 
      closed = true; 
     } 
    } 
} 

그래서 문제가 여기에 무엇 :

여기
using System; 
using System.Collections.Concurrent; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Sockets; 
using System.Net.WebSockets; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WebSocketServer 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Starting a new WebSockets server."); 
      WebSocketServer server = new WebSocketServer(); 
      Console.WriteLine("The WebSocket server has started."); 
      bool userRequestedShutdown = false; 
      while (!userRequestedShutdown) 
      { 
       Console.ReadLine(); 
       DialogResult result = MessageBox.Show("Do you want to shut the server down?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 
       if (result == DialogResult.Yes) 
       { 
        userRequestedShutdown = true; 
       } 
      } 
      server.Stop(); 
     } 

     class WebSocketServer 
     { 

      TcpListener server; 
      Thread connectionListener; 
      ConcurrentDictionary<TcpClient, Thread> clients = new ConcurrentDictionary<TcpClient, Thread>(); 

      public WebSocketServer() 
      { 
       server = new TcpListener(IPAddress.Parse("127.0.0.1"), (int)Properties.Settings.Default["Port"]); 
       try 
       { 
        server.Start(); 
       } 
       catch (Exception exception) 
       { 
        Console.WriteLine("Error while trying to start the server: {0}", exception.ToString()); 
       } 
       connectionListener = new Thread(() => 
       { 
        while (true) 
        { 
         Console.WriteLine("Waiting for a new client."); 
         try 
         { 
          TcpClient client = server.AcceptTcpClient(); 
          Thread clientListener = new Thread(() => 
          { 
           try 
           { 
            NetworkStream stream = client.GetStream(); 
            byte[] buffer = new byte[1024]; 
            Console.WriteLine("Wating for the client to write."); 
            while (client.Connected) 
            { 
             try 
             { 
              int bytesRead = stream.Read(buffer, 0, buffer.Length); 
              Console.WriteLine("Read {0} bytes from the client.", bytesRead); 
              string data = Encoding.UTF8.GetString(buffer).Substring(0, bytesRead); 
              Console.WriteLine("Read the following string from the client: {0}", data); 
             } 
             catch (Exception exception) 
             { 
              Console.WriteLine("Error while trying to read from a TCP client: {0}", exception.ToString()); 
              break; 
             } 
            } 
            Console.WriteLine("Client disconnected. Removing client."); 
           } 
           catch (Exception exception) 
           { 
            Console.WriteLine("Error while trying to connect to a TCP client: {0}", exception.ToString()); 
           } 
           client.Close(); 
           clients.TryRemove(client, out clientListener); 
          }); 
          clientListener.Start(); 
          clients.TryAdd(client, clientListener); 
         } 
         catch (Exception exception) 
         { 
          Console.WriteLine("Error while trying to accept a TCP client: {0}", exception.ToString()); 
         } 
         Console.WriteLine("A client has connected."); 
        } 
       }); 
       connectionListener.Start(); 
      } 

      public void Stop() 
      { 
       server.Stop(); 
       connectionListener.Abort(); 
      } 
     } 
    } 
} 

클라이언트 코드입니다 : 여기

는 서버 코드? Azure 가상 컴퓨터에서 서버를 호스팅 할 때 원격 컴퓨터의 모든 트래픽을 허용하도록 인바운드 및 아웃 바운드 규칙을 설정하여 원격 서버의 Windows 방화벽에서 <RemotePortNumber>으로 사용하려고하는 TCP 포트를 열었습니다 그 포트에 내 가상 머신의 호스트 이름의 외부 포트를 내 가상 머신의 내부 (개인 포트)에 매핑하는 Azure 포털에 TCP 엔드 포인트를 만들었습니다. 둘 다 일관성을 위해 동일한 포트 번호 <RemotePortNumber>을 매핑하도록 설정했습니다. 연결하려면 <MyServiceName>.cloudapp.net<Remote Hostname> 값을 사용하고 있습니다. 나는 또한 IPAddress.Parse(<Public IP of my Azure Server>)을 사용하여 스트림 연결을 시도했지만 운이 없었습니다 ... 호스트 이름을 올바르게 포맷하지 않은 것처럼 시간 초과가 발생합니다. 내가 뭘 놓치고 있니? 누구든지 문제를 디버깅하는 방법에 대한 단서를 제공 할 수 있다면 매우 유용 할 것입니다.

업데이트 업데이트 : WireShark 추적을 실행하면 이러한 메시지가 많이 표시됩니다.이 점은 좋지 않은가요? Azure의 경우 공개 도메인의 패킷을 라우팅해야한다는 점을 고려하면 TCP 재전송은 괜찮을 것으로 생각됩니다. VM의 개인 포트에 포트 있지만)가 RST, ACK의가 무엇에 대해 확실하지 :

enter image description here

업데이트 : Microsoft 메시지 분석을 실행, 내가 로컬 링크 계층에서 이러한 메시지를 참조하십시오

enter image description here

참고 : 내 VM의 내부 IP는 100.75.20.78이고 공용 IP는 191.238.37.130입니다. 공개 도메인 이름은 ovidius.cloudapp.net입니다. TCP 포트 6490에서 응용 프로그램을 호스팅하려고합니다. 포기하지 않기 위해 개인 IP 주소를 검게했습니다.

다음 내가 VM에 도메인에서 푸른 포털의 TCP 포트를 매핑 한

같이, 나는 조금있어

enter image description here

+1

힌트 : 서버에 텔넷 연결을 시도하십시오. 성공하면 문제가 클라이언트에있을 가능성이 큽니다. 그렇지 않은 경우 서버에 문제가 있습니다. –

+0

@alex 또한 traceroute를 사용하여 서버와 얼마나 멀리 떨어져 있는지 볼 수 있습니다. 응답을 클라이언트로 다시 생성하는지 확인하기 위해 서버를 tcpdump 할 수 있습니까? – CDahn

+0

@ ViníciusGobboA.deOliveira 방금 텔넷을 열려고 시도했습니다 . "포트에 호스트 연결을 열 수 없습니다."... 아마도 그 서버 ... 아마도 내 을 tracert하려고했지만 그것을 통과하고 싶지 않았어 ... 계속 요청 시간이 초과되었습니다. 아웃." – Alexandru

답변

3

(빈칸을 채워)이에 _______ 일이 어머니를 지출 한 후 라우팅 문제를 해결할 수 있는지 알아보기위한 대체 방법을 탐색하는 방법으로 창의적입니다.공용 포트를 동일한 개인 포트에 매핑 할 때 Microsoft 가상 컴퓨터 라우팅이 실패합니다. 예를 들어

, 나는 아래의 새로운 소켓 엔드 포인트를 설정했는데, 내가 이전에 WebSocketServer와 함께했던 것처럼 동일한 가상 머신 포트에 동일한 도메인 포트를 매핑하지 않았기 때문에 그것은 일 :

enter image description here

업데이트 : 또한 호스팅 할 때 IP를 127.0.0.1이 아니라 내부 IP (내 경우 100.75.20.78)로 설정해야합니다.

다시 업데이트 : 위의 해결 방법과는 달리 6490에서 이전 끝점을 삭제하고 다시 만들려고했는데 지금 그 주소에 연결할 때 작동하는 것 같습니다. 그 이유는 완전히 다르다는 것입니다. 여기서 유일한 차이점은이 시점에서 엔드 포인트를 생성하기 전에 해당 엔드 포인트의 포트를 허용하는 방화벽 규칙이 있다는 것입니다. 차이가 있는지 확실하지 않습니다. 솔직히이 문제를 일으킨 것이 확실하지 않습니다.

업데이트 그러나 다시 : 당신은 당신의 푸른 가상의 내부 IP에서 서버를 호스트 할 필요가

  1. : 그냥 좀 더 생각해 ... 나는 다음과 같은 두 가지 문제에 귀착 생각 기계, 아니 localhost 또는 127.0.0.1 내가하고 있었던 것처럼.
  2. Azure 엔드 포인트에서 "직접 서버 리 턴 실행 가능"기능을 사용하지 않아야합니다.