Search code examples
asp.net-corewebsocket.net-coremiddleware

.NET Core Middleware is not invoked


Hello i have the following problem:

I am trying to send an object from a Console Application to a ASP NET Core Server via websockets.

On the Console application i serialize an object with NewtonSoft Jsonand i send it over the Socket to the .NET Core server.

On the Server i have created a tiny middleware.The Invoke method just does not get called.

I keep two instances of visual studio open and nothing happens on the server side,until i close the connection on the client side and this error pops in on the server side - terminal :

enter image description here

1 Server

1.1 Program

    class Program
        {
            static void Main(string[] args)
            {
                BuildWebHost(args).Run();
            }
            public static IWebHost BuildWebHost(string[] args)=>

                WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseKestrel()
                .UseSockets()
                .UseUrls("http://localhost:8200")

                .Build();
        }

1.2 Startup class

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddSingleton<WebSocketService>(x=>new WebSocketService());

        }
        public void Configure(IApplicationBuilder builder)
        {

            builder.UseWebSockets();
            builder.UseMiddleware<SocketMiddleware>();


        }
    }

1.3 Middleware

class SocketMiddleware
    {
        WebSocketService handler;
        public SocketMiddleware(WebSocketService _handler,RequestDelegate del)
        {
            this.handler = _handler;
            this.next = del;
        }

        RequestDelegate next;

        public async Task Invoke(HttpContext context)
        {


            if (!context.WebSockets.IsWebSocketRequest)
            {
                await  this.next(context);
                return;
            }
            await this.handler.AddClientAsync(context.WebSockets);

        }
    }

Note: I will not post code of the service that the middleware uses since it is not relevant in this case.The invoke does not get called.

2 Client

The client just serializes a POCO class Player and sends it over the socket.It then waits for the server to respond with a list of Player.

static async Task Main(string[] args)
        {
            Player updatePlayer = new Player(100);
            List<Player> players;
            Memory<byte> buffer = new byte[2000];
            ReadOnlyMemory<byte> toSend;
            ReadOnlyMemory<byte> actualReceived;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8200);
            Random rand = new Random();

            await socket.ConnectAsync(iPEndPoint);
            using(NetworkStream stream =new NetworkStream(socket))
            {
                while (true)
                {
                    updatePlayer.Lat = rand.Next(10, 100);
                    updatePlayer.Lng = rand.Next(10, 100);

                    string data=JsonConvert.SerializeObject(updatePlayer);
                    toSend = Encoding.UTF8.GetBytes(data);
                    await stream.WriteAsync(toSend);

                    int received=await stream.ReadAsync(buffer);
                    actualReceived = buffer.Slice(0, received);
                    string msg = Encoding.UTF8.GetString(actualReceived.ToArray());
                    players = JsonConvert.DeserializeObject<List<Player>>(msg);
                    if (Console.ReadKey().Key == ConsoleKey.Escape)
                    {
                        break;
                    }

                }
            }


        }

P.S Could it be a problem that the server uses websockets and on the client i use the socket class?I figure as long as the destination address and port are okay..its just bytes.


Solution

  • In the Server.cs the Invoke method has a parameter of type WebSocketManager.

    We can accept a WebSocket connection but not a raw Socket.
    Therefore in the Client.cs i replaced the raw Socket with a WebSocket implementation.