Question

I am sending binary data using Uint8Arrays and ArrayBuffers. I am able to successfully send it by creating a new Uint8Array and ArrayBuffer every time.

For performance purposes (reducing garbage and such), I would like to reuse the same Uint8Array and ArrayBuffer for the next message. In this case, each message has the same fields so the byte length isn't a problem. I just overwrite it.

However, reuse causes the data being sent to be incorrect.

My best guess is that I am modifying the ArrayBuffer for the next message while the previous message was still in the process of sending. Is this the problem? If so, is there any way that I can detect when the ArrayBuffer is no longer being used by the WebSocket so I can pool it? If not, what else could cause this behavior?

Thanks!

Was it helpful?

Solution

Apparently the error was just a logic error on my part.

To send things in binary, I had written a Message object that used bit shifting and integer addition to fill the Uint8Array. When I wrote my reset function, I only reset the position variable and not the array values under the assumption that its functions would just overwrite the array properly.

However, since adding new values to the array used addition (array[0] += newvalue) rather than sets (array[0] = newvalue), any new data was getting corrupted by the old values.

I feel kinda dumb right now.

Dhruv Chopra and Kanaka's comments helped point me in the right direction. I tested using a 10 second interval setTimeout function and it still was giving me wrong values, which led me to realize that it was just a stupid mistake of mine. I'd like to give credit to them but I'm unaware as to how.

Still, thanks a lot for the help! I appreciate it.

EDIT: Apparently I can only answer my own question after 8 hours. I will do so tomorrow to avoid confusion.

EDIT 2: Apparently I can upvote comments now. Thanks again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top