0

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.

5
  • 1
    “I will not post code of the service that the middleware uses since it is not relevant in this case.” – Not sure I agree with that. Your middleware request is being interrupted, so it does kind of matter how you are interacting with the web socket request.. That being said, are you sure your client works? Did you try using a browser instead? Also, is there any more in the logs?
    – poke
    Commented Jun 30, 2018 at 18:16
  • I have tried the websocket client provided by chrome and it works.Also i have tried with a angular 2 js client and it still works.The Invoke method gets invoked.Why is it that the console application won't invoke it ? I suppose that it could be that i send raw Tcp and the .NET framework expects a HTTP GET ? Commented Jun 30, 2018 at 19:13
  • 1
    Did you check the WebSocket specification? WebSockets are not just bare TCP sockets, they are an upgrade of a HTTP connection, so you cannot just open up a socket like that and expect to be able to send data.
    – poke
    Commented Jun 30, 2018 at 21:26
  • Yes i am aware of the fact that first you send a HTTP request that will get upgraded to websocket (raw tcp).But how do you wrap your request to do that? I mean coming with a raw socket how should that be dealt with in C# ? Commented Jun 30, 2018 at 21:33
  • 1
    If you want to use a raw TCP socket, you will have to implement the protocol yourself. Otherwise, you should probably use a WebSocket client library.
    – poke
    Commented Jun 30, 2018 at 21:55

1 Answer 1

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.