5

At the moment I am using REST to consume data from external services/servers using my console app, but it's not very real time.

Can anyone provide a very basic working example of how I can connect a .net core console app to wss://echo.websocket.org?

I have started with:

using System;
using System.Net.WebSockets;

namespace websocket
{
    class Program
    {
        static void Main(string[] args)
        {

            using (var ws = new WebSocket("wss://echo.websocket.org"))
            {

            }

        }
    }
}

But new WebSocket("wss://echo.websocket.org")) shows the error Cannot create an instance of the abstract type or interface 'WebSocket' [websocket]csharp(CS0144)

oshirowanen
  • 15,297
  • 82
  • 198
  • 350
  • `WebSocket Class` is an abstract class in .Net, And you can't instantiate abstract classes. Please look thits link: https://learn.microsoft.com/en-us/dotnet/api/system.net.websockets.websocket?view=net-5.0 – Hasan Fathi Jan 17 '21 at 13:03
  • Try this https://www.c-sharpcorner.com/article/how-to-use-websockets-in-asp-net-core-day-nine2/ or this link: https://www.c-sharpcorner.com/article/using-websocket-to-build-real-time-application-via-asp-net-core/ to implement your WebSocket client – Hasan Fathi Jan 17 '21 at 13:26

2 Answers2

11

If you want to solve your problem using no libraries you'll have to struggle with some internals of .NET.

The following code should provide a simple working solution....

public static async Task Main(string[] args)
{
    CancellationTokenSource source = new CancellationTokenSource();
    using (var ws = new ClientWebSocket())
    {
        await ws.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None);
        byte[] buffer = new byte[256];
        while (ws.State == WebSocketState.Open)
        {
            var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Close)
            {
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                HandleMessage(buffer, result.Count);
            }
        }
    }
}

private static void HandleMessage(byte[] buffer, int count)
{
    Console.WriteLine($"Received {BitConverter.ToString(buffer, 0, count)}");
}
FloriUni
  • 346
  • 2
  • 10
  • 4
    What "struggles" are you referring to? Your code looks pretty straightforward to me (hence the upvote). – Dai Dec 24 '21 at 18:23
  • 1
    Use: https://www.piesocket.com/websocket-tester for a working wss:// url to test on. – niek tuytel Jan 17 '22 at 10:55
1

WebSocket Class is an abstract class in .Net, And you can't instantiate abstract classes.

Please look at this link: WebSocket Class.

See these sources just for a guide:

How To Use WebSockets In ASP.NET Core

Using WebSocket To Build Real-Time Application Via ASP.NET Core

ClientWebSocket example

Hasan Fathi
  • 5,610
  • 4
  • 42
  • 60