I'm sending huge chunks of JSON data through websockets. The JSON may have over 1000 entries. Due to the frame size limitation, the Websocket protocol automatically splits the JSON into frames, which cannot be helped. As we cannot change the frame size of websockets.
The problem:
When I try to evaluate my JSON using JSON.parse
it gives me a parsing error which is obvious because the frames are not complete JSON objects. All this happens in the Websocket onmessage
event callback. How can I recieve the huge JSON in differnt frames and still be able to parse it? I have tried to concat the frames in onmessage
still the error persists.
Side question:
How to concatinate a broken JSON properly?
websockets frame buffer: its size depends both on the size and the number of frames it contains. By default the maximum size is 1MB and the maximum number is 32.
A WebSocket frame can be one of 6 types: text , binary , ping , pong , close and continuation . Furthermore, every frame is either a fin frame or not. The first byte of each frame is used to represent the type of frame (known as the op code) as well as whether or not it's a fin frame.
Compared to REST, WebSockets allow for higher efficiency and are easier to scale because they do not require the HTTP request/response overhead for each message sent and received. Furthermore, the WebSocket protocol is push-based, enabling you to push data to connected clients as soon as events occur.
Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.
A single WebSocket frame, per RFC-6455 base framing, has a maximum size limit of 2^63 bytes (9,223,372,036,854,775,807 bytes ~= 9.22 exabytes) (correction by @Sebastian)
However, a WebSocket message, made up of 1 or more frames, has no limit imposed on it from the protocol level.
Each WebSocket implementation will handle message and frame limits differently. Such as setting maximum messages sizes for whole message (usually for memory consumption reasons), or offering streaming options for large messages to better utilize memory.
But in your case, it is likely that your chosen WebSocket implementation has a bug and is improperly splitting up the JSON message into multiple messages, instead of multiple frames. You can use the network inspection tooling in Chrome or an external tool like Wireshark to confirm this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With