Handle continuous JSON stream

The (now defunct) page http://stream.twitter.com/1/statuses/sample.json is used to return a continuous and infinite stream of JSON data.

I would like to process it using jQuery (or JavaScript, but preferably jQuery) inside my own web page to be able to display visual effects based on live tweets.

Since, as far as I know, the jQuery parseJSON function only performs a callback function after all the data has been sent by the server, but it is actually a continuous stream of data. How can I process the data "as it happens", but still maintain the connection?

+55
json javascript jquery stream
Jul 02 '11 at 16:13
source share
4 answers

Update 2

This is best done using WebSockets .

It looks like this:

 var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']); 

Attaching some event handlers directly to the connection lets you know when the connection opens, when you received incoming messages or an error occurred.

Sending messages is just as easy:

 connection.send('your message'); connection.send(binaryData); 

See WebSockets View: Bringing Sockets to the Internet for a complete explanation of how to do this.

You can also refer to browser support for WebSockets .

ASP.Net Developers: If for some reason you need to support older browsers and don’t want to determine how to handle those that do not support WebSockets, consider using a library such as SignalR .

Update 1

Most browsers currently implement the EventSource API , which makes long polling really easy, as long as the stream can be delivered with the text/event-stream content type. Older browsers or those developers who for some reason cannot design the stream so that this type of content can use the helper script to do the same.

Here is an example:

 var jsonStream = new EventSource('https://example.com/yourstreamingservice') jsonStream.onmessage = function (e) { var message = JSON.parse(e.data); // handle message }; 

This is basically a full version of the exact thing, which I will discuss below.

Streaming response from an old service

What you want is called a long survey. You will need the custom AJAX onreadystatechange processing function. Instead of waiting for the completion of the entire stream (since it will never be), you will need to periodically check the contents. Note that you will need to do the hard work to work in IE using an iframe .

Rough:

  • Respond to each onreadystatechange event and examine the stream that you received before the current character to see if there is enough data to consume one or more discrete events. You will need to parse the stream yourself using javascript string processing functions. To accomplish this task, you can use a combination of split, indexOf, regular expressions, loops, etc.
  • If there is still not enough content, exit and wait for the next event.
  • I am sure that every time the onreadystatechange handler onreadystatechange , the responseText will be all the data that has been received so far. Define a constant variable that will hold the position of the first character that has not yet been properly processed.
  • When there is enough content in the stream for one or more discrete events, output them one at a time and pass them to your JSON parser to actually display the text as objects. Use them as usual.

Refuse HTTP Streaming in AJAX templates for a good discussion on this exact topic (it also covers service flows, which are what you do). As indicated, if you must support IE, then you need to use the iframe method to do this.

Thus, streaming data makes the HTTP Streaming approach more flexible, because you can transfer arbitrary content, not Javascript commands, and because you can control the connection life cycle. However, it combines two technologies that are incompatible between browsers, with predictable portability issues. Experiments suggest that the page streaming technique works in both IE and Firefox, but the Streaming service only works with Firefox, whether XMLHTTPRequest or IFrame is used. In the first case, IE suppresses the response until it is completed, while the IFrame works if a workaround is used: IE receives a message from the server after the first 256 bytes, so the only thing to do is send 256 dummy bytes before sending messages. After that, all messages will arrive as expected. Thus, the full version of the streaming service is also possible in IE!

Security concerns

Regular AJAX cannot cross-domain, which means (now that I pay attention to what you want to transfer from Twitter) that you cannot do what you ask. This can be circumvented with JSONP, but JSONP by its nature cannot be streamable in maintenance, and yet, twitter is not offered. There is also Cross Resource Resource (CORS), but Twitter is not going to tweak this for you - this is what they do only for the domains associated with them. And CORS requires a modern browser.

Thus, the only option is to create a proxy service on your web server, which executes requests for twitter for you, and then transfers the data. This can only be done from the same domain from which the main page was sent. It will also allow you to create a version that will work for IE using the iframe technique. If you don't like older versions of IE, you can implement CORS yourself to defeat the domain restriction if you know the domain that will make the requests.

If you have full control over the client software (for example, if it concerns the corporate intranet), there is another option: placing a web browser inside a compiled user form of the application with local execution. I only did this with C #, but I guess this is possible from other languages. When you use the correct browser object because it is located inside the C # application, the C # application can defeat cross-domain security restrictions by reading and writing the entire contents of the page, regardless of which domain it comes from. I doubt your situation is like that, but I wanted to put this option for others who could appreciate it.

+70
Jul 02 2018-11-17T00:
source share

I have an open source project that allows this in modern browsers (and reverts to jQuery style on old ones). The syntax of the call is similar to jQuery.ajax:

http://oboejs.com

+8
Nov 04 '13 at 15:37
source share

The URL you provided in your question sends a JSON response stream. Due to cross-domain security restrictions in browsers, you cannot access it using javascript. You will need to use the server side of the server script on your server, which you could poll at regular intervals using AJAX requests or host your site on twitter.com . The first seems more doable.

+3
Jul 02 '11 at 16:22
source share

A web page at a very fundamental level cannot support a direct / running connection to the server. A web browser sends a request to the server. The server sends a response (HTML or more) back to the client (web browser). Think of it as a stateless model - no communication is ever maintained alive after completing a request and response.

Therefore, you must do it yourself. You must call additional, periodic requests from the client side.

One way is to periodically call the AJAX / GET functions using the setInterval () function. For example:

 setInterval(function() { $.ajax({ url: "mydata/get", success: function(){ // update content. } }); }, 5000); 

This will disable the AJAX request mydata / get (or any other URL that you want to use) every 5 seconds.

-12
Jul 02 '11 at 16:19
source share



All Articles