0

我在我的 Windows 商店应用程序中使用 websocket。我使用与示例连接 WebSockets 示例(Windows 8)中相同的代码。但现在我有很大的问题。我在 readBuffer 中得到字节,但服务器在某些周期中发送字节,例如消息有 20000 字节,然后服务器发送 1000 字节,然后再发送 1000 字节 ..=20000。但问题是 while(true) 因为它仍然读取字节并且在 bytesReceived 中我得到 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;
            }
        }...
4

1 回答 1

1

您可以创建一个 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 一起工作

于 2013-09-13T10:23:39.450 回答