从从 websocket 接收的字节中获取完整的字节数组

本文关键字:字节 字节数 数组 获取 websocket 从从 | 更新日期: 2023-09-27 18:31:07

我正在我的Windows应用商店应用程序中使用websocket。我使用与示例连接WebSockets示例(Windows 8)中相同的代码。但现在我遇到了大问题。我在 readBuffer 中获取字节,但服务器在某些周期中发送字节,例如消息有 20000 字节,然后服务器发送 1000 字节,然后再次发送 1000 字节..=20000。但问题是 while(true),因为它的 stil 读取字节和字节接收我得到 20000 什么是可以的,但在此之后的读取缓冲区仅包含例如 3000 字节。如何连接字节数组或如何获取结果字节数组。第二个问题是我不知道消息会有多大,这意味着如果我尝试获取一个数组,这个数组包含在尾零上,因为字节数组被声明为更大的大小,就像在现实中一样。

 private async void Scenario2ReceiveData(object state)
    {
        int bytesReceived = 0;
        try
        {
            Stream readStream = (Stream)state;
            MarshalText(OutputField, "Background read starting.'r'n");
            while (true) // Until closed and ReadAsync fails.
            {
                int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                bytesReceived += read;
            }
        }...

从从 websocket 接收的字节中获取完整的字节数组

您可以创建一个 MemoryStream 并在其上使用 ToArray:

        byte[] completeBuffer;
        using(MemoryStream memStream = new MemoryStream())
        {
            while (true) // Until closed and ReadAsync fails.
            {
                int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                if(read == 0)
                    break;
                memStream.Write(readBuffer, 0, read);
                bytesReceived += read;
            }
            completeBuffer = memStream.ToArray();
        }
        // TODO: do anything here with completeBuffer

你需要测试它,如果它适用于 async/await