Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websockets convert byte[] to string

I have the following code:

            Console.WriteLine("New Socket connection opened");
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                Console.WriteLine("New message received : "+ Encoding.UTF8.GetString(buffer));
            }

When I send Hello my client, I can see Hello????????????? on the console. Clearly, it means I have a buffer of size 1024 * 4, of which, the first few bytes are taken by Hello. How do I trim my String (eventually, I wanto pass JSON from my client to the server).

like image 518
Amarsh Avatar asked Jun 02 '26 20:06

Amarsh


1 Answers

Basically John answered this

WebSocketReceiveResult.Count Property

Indicates the number of bytes that the WebSocket received.

Count can be 0 in two cases:

The WebSocket received an empty message. In this case the CloseStatus property is None.

The WebSocket received a close message from the remote endpoint. In this case, the CloseStatus property is set to a value other than None.

GetString(Byte[], Int32, Int32)

public virtual string GetString (byte[] bytes, int index, int count);

When overridden in a derived class, decodes a sequence of bytes from the specified byte array into a string.

  • bytes Byte[] The byte array containing the sequence of bytes to decode.
  • index Int32 The index of the first byte to decode.
  • count Int32 The number of bytes to decode.

So you will need something like this

Console.WriteLine("New message received : "+ Encoding.UTF8.GetString(buffer,0,Result.Count));

However, and its a big however. There is more to go wrong, and i would seriously suggest getting a good WebSocket tutorial and some bullet proof (typical) designs

like image 183
TheGeneral Avatar answered Jun 05 '26 12:06

TheGeneral



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!