UWP无法在两个应用程序之间创建本地主机连接

时间:2019-06-15 12:54:06

标签: c# tcp uwp

我正在尝试在两个UWP应用之间建立TCP连接。当服务器和客户端都在同一应用程序中运行时,它可以正常工作。但是,当我将服务器部分移至一个应用程序并将客户端部分移至另一应用程序时,ConnectAsync会引发异常(服务器无法及时响应)。

两个应用程序都具有专用网络功能设置。从MSDN页面了解到,只要我在调试器中运行应用程序,就不必在CheckNetIsolation中添加异常。 (我选中了该项目的de debug属性页中的复选框,两者都启用了“允许本地网络环回”。

防火墙也完全关闭了。

我在netstat中看到该端口已打开并且处于侦听状态:

 TCP    0.0.0.0:1337           PC-BAS:0               LISTENING

我使用的代码是从MSDN example复制而来的,除了客户端和服务器托管在两个单独的应用程序中的部分外,其他代码均未更改。

客户:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        //this.StartServer();
        this.StartClient();
    }

    private async void StartClient()
    {
        try
        {
            // Create the StreamSocket and establish a connection to the echo server.
            using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
            {
                // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
                var hostName = new Windows.Networking.HostName("127.0.0.1");

                this.clientListBox.Items.Add("client is trying to connect...");

                await streamSocket.ConnectAsync(hostName, StreamSocketAndListenerPage.PortNumber);

                this.clientListBox.Items.Add("client connected");

                // Send a request to the echo server.
                string request = "Hello, World!";
                using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
                {
                    using (var streamWriter = new StreamWriter(outputStream))
                    {
                        await streamWriter.WriteLineAsync(request);
                        await streamWriter.FlushAsync();
                    }
                }

                this.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request));

                // Read data from the echo server.
                string response;
                using (Stream inputStream = streamSocket.InputStream.AsStreamForRead())
                {
                    using (StreamReader streamReader = new StreamReader(inputStream))
                    {
                        response = await streamReader.ReadLineAsync();
                    }
                }

                this.clientListBox.Items.Add(string.Format("client received the response: \"{0}\" ", response));
            }

            this.clientListBox.Items.Add("client closed its socket");
        }
        catch (Exception ex)
        {
            Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
            this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
        }
    }

服务器:

    protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        try
        {
            var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

            // The ConnectionReceived event is raised when connections are received.
            streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

            // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
            await streamSocketListener.BindServiceNameAsync("1337");

        }
        catch (Exception ex)
        {
            Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
        }
    }

    private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
    {
        string request;
        using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
        {
            request = await streamReader.ReadLineAsync();
        }

        // Echo the request back as the response.
        using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
        {
            using (var streamWriter = new StreamWriter(outputStream))
            {
                await streamWriter.WriteLineAsync(request);
                await streamWriter.FlushAsync();
            }
        }

        sender.Dispose();
    }

我在做什么错了?

更新

我尝试使用checknetisolation豁免这两个应用程序:

  

C:\ Users \ baspr> checknetisolation LoopbackExempt -s

     

列表环回豁免的AppContainer

     

1 ------------------------------------------ -----------------------       名称:bb9c7c66-7c8e-4736-b328-1b107e10a7a9_wkb2562a8jp2j       SID:S-1-15-2-762432806-102046223-720402593-3591906639-2980959523-756744333-221970472

     

[2] -------------------------------------------- ---------------------       名称:client_wkb2562a8jp2j       SID:S-1-15-2-2445159625-2135182799-200836335-1591194441-3000767028-3156876117-3345333685

客户端:

C:\Users\baspr>checknetisolation LoopbackExempt -a -n=client_wkb2562a8jp2j
OK.

服务器:

C:\Users\baspr>checknetisolation LoopbackExempt -a -n=bb9c7c66-7c8e-4736-b328-1b107e10a7a9_wkb2562a8jp2j
OK.

尽管我想知道是否甚至有必要,因为这在MSDN上已说明:

  

环回和调试器

     

默认情况下,在Visual Studio调试器下运行会启用出站   仅针对该调试会话自动进行环回。你不应该   只要在“环回”复选框中选中   启动项目的调试器设置。如果要实施   一个套接字侦听器,您必须为入站启用本地主机环回   连接(请参见下文)。

无论如何,它不会改变任何东西。我仍然无法连接到服务器。我尝试将我的本地IP地址都用作回送地址(192.168.1.2和127.0.0.1)。没用

希望任何人都能对此有所了解...

0 个答案:

没有答案