34

I am new in the area of websocket.

I can connect to websocket server using JavaScript using this code:

var webSocket = new WebSocket(url);

But for my application, I need to connect to the same server using c#. The code I am using is:

ClientWebSocket webSocket = null;
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(url), CancellationToken.None);

3rd line of the code results following error:

"Server returned status code 200 when status code 101 was expected"

After little bit of survey, I realised that somehow server can't switch http protocol to websocket protocol during connection process.

Am I doing anything stupid in my C# code or there is something going wrong with the server. I don't have any access to the server, as the url I am using is a third party one .

Could you please give me any suggestion regarding the issue?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Jahangir Alam
  • 353
  • 1
  • 4
  • 7

6 Answers6

25

TL; DR:

Use ReceiveAsync() in loop until Close frame is received or CancellationToken is canceled. That's how you get your messages. Sending is straightworward, just SendAsync(). Do not use CloseAsync() before CloseOutputAsync() - because you want to stop your receiving loop first. Otherwise - either the CloseAsync() would hang, or if you use CancellationToken to quit ReceiveAsync() - the CloseAsync() would throw.

I learned a lot from https://mcguirev10.com/2019/08/17/how-to-close-websocket-correctly.html .

Full answer:

Use Dotnet client, here, have an example cut out from my real life code, that illustrate how the handshaking is made. The most important thing most people don't understand about how the thing operates is that there is no magic event when a message is received. You create it yourself. How?

You just perform ReceiveAsync() in a loop that ends, when a special Close frame is received. So when you want to disconnect you have to tell the server you close with CloseOutputAsync, so it would reply with a similar Close frame to your client, so it would be able to end receiving.

My code example illustrates only the most basic, outer transmission mechanism. So you send and receive raw binary messages. At this point you cannot tell the specific server response is related to the specific request you've sent. You have to match them yourself after coding / decoding messages. Use any serialization tool for that, but many crypto currency markets use Protocol Buffers from Google. The name says it all ;)

For matching any unique random data can be used. You need tokens, in C# I use Guid class for that.

Then I use request / response matching to make request work without dependency on events. The SendRequest() methods awaits until matching response arrives, or... the connection is closed. Very handy and allows to make way more readable code than in event-based approach. Of course you can still invoke events on messages received, just make sure they are not matched to any requests that require response.

Oh, and for waiting in my async method I use SemaphoreSlim. Each request puts its own semaphore in a special dictionary, when I get the response, I find the entry by the response token, release the semaphore, dispose it, remove from the dictionary. Seems complicated, but it's actually pretty simple.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace Example {

    public class WsClient : IDisposable {

        public int ReceiveBufferSize { get; set; } = 8192;

        public async Task ConnectAsync(string url) {
            if (WS != null) {
                if (WS.State == WebSocketState.Open) return;
                else WS.Dispose();
            }
            WS = new ClientWebSocket();
            if (CTS != null) CTS.Dispose();
            CTS = new CancellationTokenSource();
            await WS.ConnectAsync(new Uri(url), CTS.Token);
            await Task.Factory.StartNew(ReceiveLoop, CTS.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        public async Task DisconnectAsync() {
            if (WS is null) return;
            // TODO: requests cleanup code, sub-protocol dependent.
            if (WS.State == WebSocketState.Open) {
                CTS.CancelAfter(TimeSpan.FromSeconds(2));
                await WS.CloseOutputAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
                await WS.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            }
            WS.Dispose();
            WS = null;
            CTS.Dispose();
            CTS = null;
        }

        private async Task ReceiveLoop() {
            var loopToken = CTS.Token;
            MemoryStream outputStream = null;
            WebSocketReceiveResult receiveResult = null;
            var buffer = new byte[ReceiveBufferSize];
            try {
                while (!loopToken.IsCancellationRequested) {
                    outputStream = new MemoryStream(ReceiveBufferSize);
                    do {
                        receiveResult = await WS.ReceiveAsync(buffer, CTS.Token);
                        if (receiveResult.MessageType != WebSocketMessageType.Close)
                            outputStream.Write(buffer, 0, receiveResult.Count);
                    }
                    while (!receiveResult.EndOfMessage);
                    if (receiveResult.MessageType == WebSocketMessageType.Close) break;
                    outputStream.Position = 0;
                    ResponseReceived(outputStream);
                }
            }
            catch (TaskCanceledException) { }
            finally {
                outputStream?.Dispose();
            }
        }

        private async Task<ResponseType> SendMessageAsync<RequestType>(RequestType message) {
            // TODO: handle serializing requests and deserializing responses, handle matching responses to the requests.
        }

        private void ResponseReceived(Stream inputStream) {
            // TODO: handle deserializing responses and matching them to the requests.
            // IMPORTANT: DON'T FORGET TO DISPOSE THE inputStream!
        }

        public void Dispose() => DisconnectAsync().Wait();

        private ClientWebSocket WS;
        private CancellationTokenSource CTS;
        
    }

}

BTW, why use other libraries than the .NET built in? I can't find any reason other than maybe poor documentation of the Microsoft's classes. Maybe - if for some really weird reason you would want to use modern WebSocket transport with an ancient .NET Framework ;)

Oh, and I haven't tested the example. It's taken from the tested code, but all inner protocol parts were removed to leave only the transport part.

kevinarpe
  • 20,319
  • 26
  • 127
  • 154
Harry
  • 4,524
  • 4
  • 42
  • 81
  • Thanks for that! I get errors when CloseOutputAsync is called with WebSocketCloseStatus.Empty. Calling it with WebSocketCloseStatus.NormalClosure seems to fix them. – LachoTomov Oct 22 '20 at 10:11
  • Do you have a sample implementation for task SendMessageAsync, with a sample request & response type? This is new to me, and just pasting this code in VS.NET it complains that "not all code paths return a value" and that I either remove the async modifier, make it synchronous, or remove the member/method. I assume the other thing to do is actually implement the function, but I could use an example. – David Apr 28 '21 at 05:02
  • 1
    I changed SendMessageAsync to the following and worked perfectly for me ... public async Task SendMessageAsync(string message) { ArraySegment bytesToSend = new ArraySegment(Encoding.UTF8.GetBytes(message)); await WS.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None); } – Sean Griffin Dec 12 '21 at 05:23
  • 1
    I think I've changed the code in my library to fix some edge cases. I plan to release the full sources next week. My real world use is IoT that must handle gracefully events like vanishing Wi-Fi signal or power outages. Testing WS in such conditions allowed me to observe a lot of edge cases and find an optimal solution for each one. My final finding is - eventually - it will always throw ;) If you pull the plug. But good code will throw exceptions only on really exceptional conditions like abrupt physical disconnection. Making the client reconnect full auto is next level. – Harry Dec 13 '21 at 09:51
11

Since WebsocketSharp is not .NET Core compatible I suggest using websocket-client instead. Here's some sample code

static async Task Main(string[] args)
{
    var url = new Uri("wss://echo.websocket.org");
    var exitEvent = new ManualResetEvent(false);

    using (var client = new WebsocketClient(url))
    {
        client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message: {msg}"));
        await client.Start();

        await client.Send("Echo");

        exitEvent.WaitOne();
    }

    Console.ReadLine();
}

Be sure to use ManualResetEvent. Otherwise it doesn't work.

Gangula
  • 5,193
  • 4
  • 30
  • 59
Bohdan Stupak
  • 1,455
  • 8
  • 15
  • There is a [WebsocketSharp.Core](https://github.com/ImoutoChan/websocket-sharp-core) port (Client side) that is working for me in both Core 2.2 and 3.0. – David Woods Oct 23 '19 at 23:48
  • Nice to know. I haven't seen activity in this port's repo for awhile so I was in doubt whether it is worth trying out. – Bohdan Stupak Oct 24 '19 at 05:31
  • for instant message send use await client.SendInstant("Echo") – Roshan Jun 27 '20 at 10:27
5

If you connect with a WebSocket client and you get an HTTP 200 as response, means that probably you are connecting to the wrong place (host, path and/or port).

Basically, you are connecting to a normal HTTP endpoint that is not understanding your WebSocket requirement, and it is just returning the "OK" response (HTTP 200). Probably the WebSocket server runs in another port or path in the same server.

Check your URL.

vtortola
  • 34,709
  • 29
  • 161
  • 263
3

Not quite sure what happened to WebSocketSharp nuget package, however I noticed that now WebSocket# is showing up as most relevant result in nuget repo. It took me some time before I realized that Connect() is now returning Task, hopefully this example will be useful to someone:

using System;
using System.Threading.Tasks;
using WebSocketSharp;

namespace Example
{
    class Program
    {
        private static void Main(string[] args)
        {
            using (var ws = new WebSocket(url: "ws://localhost:1337", onMessage: OnMessage, onError: OnError))
            {
                ws.Connect().Wait();
                ws.Send("Hey, Server!").Wait();
                Console.ReadKey(true);
            }
        }

        private static Task OnError(ErrorEventArgs errorEventArgs)
        {
            Console.Write("Error: {0}, Exception: {1}", errorEventArgs.Message, errorEventArgs.Exception);
            return Task.FromResult(0);
        }

        private static Task OnMessage(MessageEventArgs messageEventArgs)
        {
            Console.Write("Message received: {0}", messageEventArgs.Text.ReadToEnd());
            return Task.FromResult(0);
        }
    }
}
Vladimirs
  • 8,232
  • 4
  • 43
  • 79
  • Shouldn't enclose the ws in a using cause it's getting closed too soon and the response is never received. but works as for 2 july 2019 – John Jul 02 '19 at 14:19
  • @John the `Console.ReadKey` will not allow the code to leave the using block, so no cleanup will be executed before pressing a key – mBardos Jul 27 '21 at 11:14
3

All the libraries mentioned above are Wrappers. The .Net Frameworks class doing this is System.Net.WebSockets.ClientWebSocket

2

Websocket URLs should start with ws:// or wss:// where the latter is secure websocket.

Babu James
  • 2,740
  • 4
  • 33
  • 50