How to create a web socket client in C#?

I have a server in php and a WebSocket client in js in the browser. How to create a connection socket with the same server in C# via the tcp protocol? I use the standard library System. Net. WebSockets.

1 answers

I never used sockets, I decided to figure it out and this is what I got in the end:

As a server for sending, I will take Echo server websocket.org.

  • And so, the main client class for web sockets is ClientWebSocket, we have it IDisposable, which means we use using:

    using var ws = new ClientWebSocket();
    

    I use c# 8, so I have using in one line.

  • Then we look at what methods this object has and notice that in fact there are there are 3 main methods in total (ConnectAsync(), SendAsync() and ReceiveAsync(). Let's now go in order:

    • ConnectAsync() - Connecting to the specified server, the input accepts two parameters (Uri and CancellationToken).

      await ws.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None);
      
    • SendAsync() - Sends an array of bytes to the server indicating the type of the sent message. Accepts ArraySegment<byte>, WebSocketMessageType, bool and CancellationToken:

      ArraySegment<byte> arraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Привет мир!"));
      await ws.SendAsync(arraySegment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
      
    • ReceiveAsync() - Receives a response from the server. Accepts ArraySegment<byte> as a buffer for writing data, and CancellationToken.

      ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]);
      WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
      var response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count);
      

That's actually all that is needed for the simplest work with web sockets in C#.
From the comments:

  1. CancellationToken - I used a stub everywhere, for example, it will do, but in the project it is better to create an object CancellationTokenSource, take a token from it and work with it. Otherwise, you are unlikely to complete the task correctly.

  2. ReceiveAsync() - before receiving the data, you should probably check whether there is a connection at all. This is done approximately so:

    if (ws.State == WebSocketState.Open)
    {
        //Мы подключились и можем отправлять данные.
    }
    

    On the Internet, I saw what they do while cycle, which turns to infinity, until the status Open, then see for yourself how you need it.

 2
Author: EvgeniyZ, 2020-01-12 16:49:37