JavaScript data push

Source: Internet
Author: User

We use Ajax to interact with background services, often by triggering events to single-touch, but for some Web applications, the foreground and background are required to maintain long connections, the front-end to receive background push data information,

For example: Stock market analysis, chat rooms and web games online.

How do you do it?

The most stupid way: the front-end needs to send an AJAX to the server once in a while, the request cost is too expensive, like, every time you have a gun, you have to open a room, or rent a cheaper house cost-effective.

So you can't do this.

1.comet

principle : Comet is a server push technology based on HTTP long connection, is a Web application architecture, the server will proactively push the data to the client program asynchronously, without requiring the client to display the request,

After the current end connects with the server once, keep the long link, let the server do push, the server uses the cache technology to realize

Comet is ideal for event-driven Web applications, and for applications that are highly interactive and real-time demanding.

front-end JS code

varXHR = (function(){    if(typeofXMLHttpRequest! =undefined) {           return NewXMLHttpRequest}Else{           return NewActiveXObject ("Microsoft.XMLHTTP")}}); Xhr.open ("GET", URL,true); xhr.send (data); Xhr.onreadystatechange=function(){      if(Xhr.readystate = = 3){        if(Xhr.status = = 200) {xhr.responsetext; }      }};

Background code (implemented here in PHP)

<?PHP//Setting the response output header        Header("Content-type:application/json;charset=utf-8"); Header("cache-control:max-age=0");//Remove Cache        $i= 0;  while($i<9){             $i++; $res= ["Success" = "OK", "text" =>i];//Results             EchoJson_encode ($res); //refresh the page stream without caching             Ob_flush(); Flush(); End Stream}?>

2.websocket

No network requests, save resources

Front:

varSocket,state=-1;functionConnect () {Console.Log("Connection Begin:"); if(Socket = =NULL|| Socket.readystate! = 1) {Socket=NewWebSocket (host); } Socket. onerror =function() {Console.Log("Connection error!")} socket. OnOpen =function(e) {Console.Log("Connection isavaliable!"); } Socket. OnMessage =function(e) {Console.Log("Receive servermessage beign:"); Document. Queryselector ("#txtarea"). InnerHTML = e.data; Console.Log("Receive servermessage end!"); } Socket. OnClose =function(e) {Console.Log("Connection closed!"); Document. Queryselector ("#txtarea"). InnerHTML + = "/n" + Event.wasclean + ";" + Event.code + ";" + event.reason; }}functionSend () {if(Socket.readystate = = 1) {Console.Log("Send Message Begin:"); varText = Document.queryselector ("#text").value; varMessage = {             Time:New Date(),clientId: "049";        }; if(text== "" | | | message = =NULL) {Console.Log("No Date to send!"); return; } Socket. Send (JSON.stringify (message)); Socket.Send (text); Console.Log("Send Message end!"); }Else{Console.Log("Connection not aviliable,please create connection!"); }}/** * Web Socket can be closed at any time, no restrictions * can be controlled according to requirements*/functionDisconnect () {Console.Log("Close Connection Begin:"); Socket.close ();}

Backend: Need to use node, the individual does not understand node, just read a little bit, if written wrong, please forgive me! Go to his place, the tube she is not good-looking, her own gun, tears also have to play

varSYS =require(' sys ');varWS =require(' WebSocket ');varServer = ws.createserver (); Server. AddEventListener (' Connection ',function(conn) {//When the client is connectedConn.send (' Hi, ' +conn.id);//send a message to the clientConn.addeventlistener (' message ',function(msg) {//When you receive a message from a clientConsole.Log(' recieved message: ' +msg); varI=0;  while(i<9) {i++; Server. Broadcast (i);//broadcast messages to all clientsConn.send (i); }    });}); Server. AddEventListener (' Close ',function(conn) {server. Broadcast (' Disconnected: ' + conn.( ID);}); Server. Listen (8000); console.Log(' Hello,server is running:8000 ');

3.SSE mode

Sse:server-send Event Browser New API

No Ajax required for real-time dynamic refresh of data

var New EventSource (URL); function init () {     function() {         Console.log (this. readyState);     }      function (e) {         console.log (' recieve: ' + e.data);    }      function (e) {         console.log (' error ');}    } Init ();

Backstage: or PHP, please call me brother P

<? PHP     // Setting the response output header    Header ("Content-type:text/event-stream;charset=utf-8");    Header ("access-control-aollow-origin:http:/ip/");    " Data: It's Beijing time: ". Date (' H:i:s ')." <br/> "?>

With the development of H5, individuals believe that this data push technology will be more widely used

JavaScript data push

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.