2016-11-07 64 views
0

我正在通過Windows通用應用程序偵聽連接,並希望通過Windows控制檯應用程序連接到該應用程序。我已經完成了一些我認爲應該連接的基本代碼,但是我從控制檯應用程序中收到了一個超時錯誤。如何從控制檯應用程序連接到Windows通用應用程序StreamSocket?

{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.5:1771"} 

Windows通用應用程序甚至不會進入連接接收功能。

服務器(UWP):

public async void SetupServer() 
    { 
     try 
     { 
      //Create a StreamSocketListener to start listening for TCP connections. 
      Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener(); 

      //Hook up an event handler to call when connections are received. 
      socketListener.ConnectionReceived += SocketListener_ConnectionReceived; 

      //Get Our IP Address that we will host on. 
      IReadOnlyList<HostName> hosts = NetworkInformation.GetHostNames(); 
      HostName myName = hosts[3]; 

      //Assign our IP Address 
      ipTextBlock.Text = myName.DisplayName+":1771"; 
      ipTextBlock.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255,0,255,0)); 

      //Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use. 
      await socketListener.BindEndpointAsync(myName, "1771"); 
     } 
     catch (Exception e) 
     { 
      //Handle exception. 
     } 
    } 

客戶端(控制檯應用程序):

static void Main(string[] args) 
    { 
     try 
     { 
      byte[] data = new byte[1024]; 
      int sent; 
      string ip = "192.168.0.5"; 
      int port = 1771; 
      IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port); 
      TcpClient client = new TcpClient(); 
      client.Connect(ipep); //**************Stalls HERE************ 
      using (NetworkStream ns = client.GetStream()) 
      { 
       using (StreamReader sr = new StreamReader(ns)) 
       { 
        using (StreamWriter sw = new StreamWriter(ns)) 
        { 
         sw.WriteLine("Hello!"); 
         sw.Flush(); 
         System.Threading.Thread.Sleep(1000); 
         Console.WriteLine("Response: " + sr.ReadLine()); 
        } 
       } 
      } 
     } 
     catch (Exception e) 
     { 

     } 
    } 

回答

1

我已經測試過在我的身邊你的代碼,它可以很好地工作。所以你的代碼沒有問題。但是我可以通過在同一設備上運行服務器和客戶端來重現您的問題,客戶端將拋出與上面顯示的相同的異常。所以請確保你從另一臺機器連接。我們無法從運行在同一臺計算機上的其他應用或進程連接到uwp應用StreamSocketListener,這是不允許的。即使免除loopback

另請確保已啓用Internet(Client&Server)capability。在客戶端上,您可以成功地ping服務器192.168.0.5

+0

謝謝我沒有意識到我無法在同一臺機器上運行它們。這是爲什麼?它會被修復嗎? –

+0

@SethKitchen,這不是一個錯誤,這是設計。這受到網絡隔離的限制。可能出於安全原因。 –

+0

我讀到了「注意:作爲網絡隔離的一部分,系統禁止通過本地環回地址(127.0.0.0)或明確指定本地IP地址在同一臺機器上運行的兩個UWP應用程序之間建立套接字連接(套接字或WinSock) 「在https://docs.microsoft.com/en-us/windows/uwp/networking/sockets - 但爲什麼我不能像本地瀏覽器那樣從非UWP應用程序連接?不要明白什麼是安全問題,尤其是當他們不允許使用IP地址並至少打開一些防火牆端口時 –