How to make a client websocket connection in ASP Net Core

-1

I am developing an Net Core console application to open websocket connections to third party websocket servers, and it is being surpringsingly difficult to find websocket client libraries written in C#. What I have tried so far:

  • WebSocketSharp: the simplest and only working one I have been able to find. However, it shows compilation warnings because it is not a Net Core package (Package 'WebSocketSharp 1.0.3-rc11' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.).
  • Class ClientWebSocket in namespace System.Net.Websockets. I have not been able to make it work, and there is few documentation about it.
  • SignalR .NET client allows you to connect to a hub, but it seems it is not meant to connect directly to a third party web socket, at least I have not found the way.

It has been surprising for me that it seems there is not standard way of connecting to a third party websocket using .NET, or at least there is no well documented way of doing it. Am I missing something? Which is the standard way of connecting directly to a web socket in .NET Core?.

Update

As requested, I add the code I did not make to work using ClientWebSocket:

Console.WriteLine("Connecting...");
            cancellationToken = new CancellationToken();
            client = new ClientWebSocket();
            await client.ConnectAsync(new Uri(@"ws://localhost:63664/api/v1.0/messages?topic=test&useToPublish=true"), new CancellationToken());
            Console.WriteLine("Connected, waiting for messages...");
            var message = await getMessageAsync();
            Console.WriteLine($"{message.ToString()}");
            Console.ReadKey(true);

Upon execution this client program shows

Connecting...

and terminates abruptly but without error. The server side shows the following exception:

System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake. ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ConnectionResetException: Error -4077 ECONNRESET connection reset by peer ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: Error -4077 ECONNRESET connection reset by peer
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.PipeCompletion.ThrowFailed()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines.Pipe.GetResult(ReadResult& result)

I am able to read the query parameters topic and useToPublish in the server side before the exception is thrown.

c#
asp.net-core
websocket
asked on Stack Overflow Aug 9, 2018 by joanlofe • edited Aug 9, 2018 by joanlofe

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0