1

I am trying to create a bot which that listen to an WebSocket URL with C# and ASP.Net Core 2.2.

But I’m new in WebSocket area.

I read Microsoft documentation about WebSocket and ClientWebSocket to solve my problem. but there are not help to me.

How my app can listen to an external WebSocket URL and react to incoming messages ?

I tried below code but get "Cannot create an instance of the abstract class or interface 'WebSocket'." error.

using (var ws = new WebSocket("wss://ws.example.com"))
{
    ws.OnMessage += (sender, e) =>
        Console.WriteLine("Message received" + e.Data);
    ws.OnError += (sender, e) =>
        Console.WriteLine("Error: " + e.Message);
    ws.Connect();
        Console.ReadKey(true);
}
8
  • what did you try and what didn't work? You need to be more specific in your question as this is not the place to outsource code writing for free to the internet Commented Apr 8, 2019 at 10:54
  • Are you trying to get streaming messages like xml data?
    – jdweng
    Commented Apr 8, 2019 at 11:01
  • @jdweng no, like json data Commented Apr 8, 2019 at 11:06
  • @DenisSchaf I told which I am new in the websocket area and all of my code which I was trying were not helpful. Commented Apr 8, 2019 at 11:09
  • 1
    WebSocket is an abstract class , you can use ClientWebSocket`. Commented Apr 8, 2019 at 11:39

1 Answer 1

1

This should do it in the base case scenario.

 public class Listener
    {
        public void StopListening()
        {
            this.src.Cancel();
        }
        private Task listenTask;
        private CancellationTokenSource src=new CancellationTokenSource();
        public Task Listen(string url)
        {

           listenTask = Task.Run(async () =>
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    await socket.ConnectAsync(new Uri(url), CancellationToken.None);
                    while (true)
                    {
                        WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                        string data = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        Console.WriteLine(data);
                    }
                }
                catch (Exception ex)
                {
                    //treat exception
                }
            },src.Token);
        }
    }

However if you plan to create multiple Listener objects ( in the context of a HttpController that on a route opens sockets ) then things change.

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