简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM