gpt4 book ai didi

c# - Websockets 将 byte[] 转换为字符串

转载 作者:行者123 更新时间:2023-12-04 02:57:19 24 4
gpt4 key购买 nike

我有以下代码:

            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 占用。我如何修剪我的字符串(最终,我想将 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 教程和一些防弹(典型)设计

关于c# - Websockets 将 byte[] 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com