Advice: if you're looking to use this on production, better take a look at https://github.com/eBay/jsonpipe
Keeping the clients updated in real time apps is quite challenging sometimes, websockets or webrtc are great for this task, but usually what the developer want is to send most of the data well timed to the client, then recive a few commands from the client, so having full duplex socket in this scenario is quite wasteful, and may pose a security risk, at allowing the user to continuosly send arbitrary data. Polled ajax request, in the other hand cant be in any way correctly timed, so this function acts as an intermediante point between ajax requests and websockets.
This function needs a request that is kept alive then chunked data is being sent. It can be binary data, strings, or serializable json objects. You will have to place chunked headers Transfer-Encoding: chunked
and ping regularly (5s should be fine) sending some data in order to maintain the connection open (routers will drop connections where data not flow as stalled or timed out).
Note that using ondata/onstring could result in merged data from different packets sent consecutively. onjson incorporates some basic pattern matching to split them and call its callback for each json item recieved. You may use some delimiter if you need to accurately identify different chunks, for example onjson will find "}{" as delimiter, theres also implemented an h264 NALu video parser for Broadway.js decoding, h264 frames always start with magic header <0,0,0,1> so its delimited accordingly. You can also implement your own protocol extending ondata.
It has different optional callback methods as described below: