3

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).

4
  • 2
    .Count ? Commented Sep 14, 2018 at 2:54
  • buffer.Count() and buffer.Length() both return 4096 Commented Sep 14, 2018 at 2:56
  • Can you show the code that's sending the message? Commented Sep 14, 2018 at 2:57
  • learn.microsoft.com/en-us/aspnet/core/fundamentals/… - all I am trying to do is Console.WriteLine() the message Commented Sep 14, 2018 at 2:59

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.