Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a client websocket based console app

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)

like image 848
oshirowanen Avatar asked Jul 14 '26 02:07

oshirowanen


1 Answers

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)}");
}
like image 187
FloriUni Avatar answered Jul 16 '26 15:07

FloriUni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!