0
votes

I have this code which works fine for project type of Console App (.NET Core).

class Program
{
    static void Main(string[] args)
    {
        var L = new TcpListener(IPAddress.Any, 4994);
        L.Start();

        using (var C = L.AcceptTcpClientAsync().Result)
        {
            var S = C.GetStream();

            var BR = new BinaryReader(S);
            var BW = new BinaryWriter(S);

            BW.Write("This is from Console!!!");
            Console.WriteLine(BR.ReadString());
        }
    }
}

But when I use this code in project type of Blank App (Universal Windows) like this:

public MainPage()
{
    InitializeComponent();

    ThreadPool.RunAsync(foo);
}

static void foo(IAsyncAction operation)
{
    var L = new TcpListener(IPAddress.Any, 4994);
    L.Start();

    using (var C = L.AcceptTcpClientAsync().Result)
    {
        var S = C.GetStream();

        var BR = new BinaryReader(S);
        var BW = new BinaryWriter(S);

        BW.Write("This is from UWP!!!");
        Debug.Write(BR.ReadString());
    }
}

It will listen to that port when I check it by netstat but when the client wants to connect this exception will be thrown.

System.Net.Sockets.SocketException: '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'

The UWP App has Private Networks (Client & Server) and Internet (Client & Server) capabilities.

Turning firewall on and off didn't help.

Target Version: Windows 10 Creators Update (10.0; Build 15063)

Client Code which is a WPF application:

using (var C = new TcpClient("127.0.0.1", 4994))
{
    var S = C.GetStream();

    var BR = new BinaryReader(S);
    var BW = new BinaryWriter(S);

    BW.Write("This is a test");
    MessageBox.Show(BR.ReadString());
}
1
Are you trying to access the socket from the same machine? Check the network isolation toolPeter Torr - MSFT

1 Answers

0
votes

Debugging UWP & TCP listeners from localhost has always been problematic. Your code is OK and it should work if you try to connect into it from an external computer. The issue you're seeing is quite likely a bug/hyper-v issue/networking problem in the network isolation.

You can check if the network isolation for your app is enabled (it is by default) running the following from command prompt:

CheckNetIsolation.exe LoopbackExempt -s

My recommendation is to use an external computer to make sure that your code is fine (it should be). After that you can try to fight with the network isolation but that can be frustrating.

Here's an another issue where this has been discussed: Unable to access TCP Server inside a Windows Universal Application