oshirowanen
oshirowanen

Reputation: 15925

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)

Upvotes: 7

Views: 16933

Answers (3)

Sam Hobbs
Sam Hobbs

Reputation: 2881

The code in WebSockets support in .NET - .NET | Microsoft Learn works, at least the HTTP/1.1 part. Except for the URI use wss://echo.websocket.org.

The following works for me:

    Uri uri = new("wss://echo.websocket.org");

    using SocketsHttpHandler handler = new();
    using ClientWebSocket ws = new();
    CancellationToken cancellationToken = new();
    await ws.ConnectAsync(uri, new HttpMessageInvoker(handler), cancellationToken);

    var bytes = new byte[1024];
    System.Net.WebSockets.WebSocketReceiveResult result = await ws.ReceiveAsync(bytes, default);
    string res = Encoding.UTF8.GetString(bytes, 0, result.Count);

    await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closed", default);
    Console.WriteLine($"Result ({result.Count} bytes): {res}");

Upvotes: 0

Hasan Fathi
Hasan Fathi

Reputation: 6106

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

Upvotes: 1

FloriUni
FloriUni

Reputation: 396

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)}");
}

Upvotes: 16

Related Questions