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

时间:2013-09-13 10:16:40

标签: c# windows-8 windows-store-apps byte

我在我的Windows应用商店中使用websocket。我使用与示例连接WebSockets示例中的相同代码(Windows 8)。但现在我有很大的问题。我在readBuffer中获取字节但服务器在某些周期中发送字节,例如消息有20000字节,然后服务器发送1000字节,然后再发送1000字节.. = 20000。但问题是while(true)因为它的stil读取字节并且以字节为单位接受我得到20000什么是好的但是readbuffer之后只包含例如3000bytes。我如何加入字节数组或如何获得结果字节数组。第二个问题是我不知道消息有多大意味着如果我尝试获得一个数组,这个数组包含在结束零上,因为字节数组被声明为更大的大小,就像在实际中一样。

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

1 个答案:

答案 0 :(得分: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