0

I m using websocket in my windows store app. I use the same code like was in sample Connecting with WebSockets sample (Windows 8). But now I have big problem. I get bytes in readBuffer but server sending bytes in some cycles for example message have 20000 bytes then server send 1000 bytes then again 1000 bytes ..=20000. But problem is while(true) because its stil read bytes and in bytesReceived I get 20000 what is ok but readbuffer after this contain only for example 3000bytes. How I can join bytes array or how I can get result byte array. Second problem is I dont know how big will be message thats means if I try get one array this this array contains on end zeros because byte array is declared for bigger size like is in real.

 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 Answer 1

1

You could create a MemoryStream and use the ToArray on it:

        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

U need to test it, if it works with async/await

Sign up to request clarification or add additional context in comments.

6 Comments

hm but completeBuffer = memStream.ToArray(); is unreachable .(
I test it again and it doesnt work because ompleteBuffer = memStream.ToArray(); is unreachable. Everything after while} is unreachable,.
because of the exception ReadAsync gives? Or does it stay inside the while? I updated the answer (see read == 0)
If the ReadAsync throws an exception, you should move the memorystream declaration outside the try/catch
no there is not exception. But when while cycle is done compiler go out of method void Scenario2ReceiveData thats mean completeBuffer = memStream.ToArray(); is not processed because the compiler not go there. Example>dropbox.com/s/25peqbifed8rytw/pr.PNG. Grey text is will never performed
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.