如何从控制台应用程序连接到Windows Universal App StreamSocket?

时间:2016-11-07 20:43:25

标签: c# sockets tcp win-universal-app

我正在通过Windows通用应用程序监听连接,并希望通过Windows控制台应用程序连接到该应用程序。我已经完成了一些我认为应该连接的基本代码,但是我从控制台应用程序收到了超时错误。

{"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 个答案:

答案 0 :(得分:1)

我已经测试了你的代码,它可以很好地运行。所以你的代码没有任何问题。但我可以通过在同一设备上运行服务器和客户端来重现您的问题,客户端将抛出与您上面显示的相同的异常。所以请确保您从另一台机器连接。我们无法从运行在同一台计算机上的其他应用或进程连接到uwp应用StreamSocketListener,这是不允许的。甚至没有loopback豁免。

另请确保已启用Internet(Client&Server) capability。在客户端上,您可以成功ping通服务器192.168.0.5