SignalR and TCP/Socket Connection

By | July 19, 2018
Questions:

Need some help with this:

I’m trying to develop a web application (asp.net core 2.1) that’s going to be connected to different devices. All of these are going to send data through a socket so I need to listen to traffic on different IPs.
I can easily listen to traffic at an IP using code similar to this. However when I incorporate that to my Program.cs Main method it doesn’t work. If I comment out BuildWebHost(args).Run(); I can listen to the port and even send myself some data using netcat (nc 127.0.0.1 10000 < hobbit.txt). There’s also this article that explains how to do this. However, none of the examples support running the web server (kestrel) along with the TcpListener.

The idea is to listen to data on different IPs (each in its own background thread maybe) and then broadcast the traffic to the web application using SignalR.

Any help with this is appreciated.

Thanks,

Here’s the sample code:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
        Listen().Wait();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

    static async Task Listen()
    {
        var ipAddress = IPAddress.Parse("127.0.0.1");
        // var listener = new TcpListener(IPAddress.Any, 10000);
        var listener = new TcpListener(ipAddress, 10000);
        listener.Start();
        Console.WriteLine("Waiting for a connection");
        var socket = await listener.AcceptSocketAsync();
        Console.WriteLine("Client connected!");
    }
}

edit
The main issue with the code is that execution stops at BuildWebHost(). The Listen() method is never executed. As stated in the question, this works fine if I comment BuildWebHost(). Any reason why kestrel can’t run with the TcpListener?

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *