Websockets 将 byte[] 转换为字符串

Websockets convert byte[] to string

我有以下代码:

            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));
            }

当我发送 Hello 我的客户端时,我可以在控制台上看到 Hello?????????????。显然,这意味着我有一个大小为 1024 * 4 的缓冲区,其中前几个字节被 Hello 占用。我如何 trim 我的字符串(最终,我想将 JSON 从我的客户端传递到服务器)。

基本上John回答了这个

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.

所以你需要这样的东西

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

不过,还是个大不过。还有更多错误,我会认真地建议获得一个好的 WebSocket 教程和一些防弹(典型)设计