Real-time web chat js and jQuery implement ajax long polling

Real-time web chat jsandjQueryimplementajaxlong polling

As we all know, the HTTP protocol is stateless, so a request is a single event, and there is no connection between the previous and the next. Therefore, we encountered a problem when solving the real-time chat of web pages, how to ensure long-term contact with the server, so as to obtain information continuously.

There are a few ways to do it all the time:

1. Long connection, that is, the server does not disconnect from the connection. The PHP server uses the ob series of functions to continuously read the output, but it consumes a lot of server resources.

2. Flash socket , the as3 language of flash, creates a socket server to process information.

3. Polling, as the name implies, is to continuously send query messages, and update them as soon as there are new messages, but there will be many useless requests.

4. Long polling is an upgraded version of polling and requires the cooperation of the server.

5. websocket , the communication function of HTML5, establishes a dedicated interface ws protocol with the server side to communicate, compatibility may become a problem, study this another day.

There are two ways of JS and JQ (in fact, the difference is the implementation of js and jq ) to implement AJAX long polling.


 

The idea of ​​long polling:

As shown in the figure: Using AJAX to send query information, the server enters an infinite wait when there is no information to return . Due to the asynchronous nature of AJAX , PHP 's execution of the wait on the server side will not affect the normal processing of the page. Once the server queries the return information, the server returns the information, AJAX uses the callback function to process this information, and quickly sends a request again to wait for the server to process.

Compared with traditional polling, long polling waits when the server does not return information, which reduces the numerous empty replies of ordinary polling servers. It can be argued that long polling makes the server's return more purposeful each time, rather than blindly returning.


 

Server-side implementation of long polling:

Chat information storage:

The database is designed as information ID (msgid) , sender (sender) , receiver (receiver) , information content (content) , the purpose of setting senderRead and receiverRead is to mark whether the information has been read, and change the mark after reading to distinguish Whether the information has been read.

createtable msg{

 

  msgid intnotnullprimarykey auto_increment,

 

  sender char(16) notnull,

 

  receiver char(16) notnull,

 

  content text ,     // The information content uses the text type, and the storage capacity can reach 65535 characters

 

  senderRead tinyint enum(0,1) default0,

 

  receiverRead tinyint enum( 0 , 1 ) default 0 // Set a read flag   

 

}

PHP script:

 The main purpose of the script is to process each query from ajax . Ajax queries the database every time to see if there is any new information. If not, just use the usleep() function to wait for a second and then query again until new information is inserted. The database is found, the script returns the queried data, and exits the infinite loop, ending the script.

  set_time_limit (0); // Set the script timeout to unlimited, otherwise the script will be automatically closed after the timeout and the polling will fail.

 

  $link=newmysqli("host","user","password","database");

 

  $search = "selectsender,receiver,content from msg where receiverRead=0 limit 1"; // Limit to read one piece of data at a time, easy to modify its read flag

 

  $change="update chatset receiverRead=1 where receiverRead=0 limit 1";

 

  while ( true ) {    // enter infinite loop

 

  $res = $link ->query( $sql );  // Query result

 

     if ( $res ->num_rows!=0){  // Read information when there is unread information

 

      $link ->query( $change ); // Set the read flag of the message to 1

 

      $msg=$res->fetch_assoc();

 

      $jsonstr =json_encode( $msg ); // Get the information, transcode the information into json format, and return it to JS

 

      echo $jsonstr ;

 

      break ; // Exit the while loop after outputting information and end the current script

 

        }

 

    usleep (1000); // If there is no information, it will not enter the if block, but it will execute and wait for 1 second to prevent PHP from suspended animation due to looping.

 

  }


 

Client implementation:

The main task of the client is to set up an ajax request function, which is called every time a query is made. When no information is returned, the server is put on hold and the current page is executed normally; when there is information returned, the function processes the returned data and is quickly called again. This function sends a request.

With native JS :

function link(){

 

    var xhr= null ; // First set xhr to be empty, in order to call the function again to reuse xhr when polling, cause an error

 

    xhr=newXMLHttpRequest();

 

    xhr.open('GET','serviceback.php', true ); // The third parameter must be set to true , asynchronous and non-blocking, and will not affect the execution of subsequent JS.

 

    xhr.send();

 

    xhr.onreadystatechange=function(){

 

    if (xhr.readyState==4) { strict can also be used (xhr.readyState==4 && xhr.status ==200 ) to limit the server response code to 200 before processing.

 

        if(xhr.responseText!=''){

 

                   process...  // The server returns the information, and the returned information is not empty, it starts to process the returned information.

 

             }

 

          setTimeout("link()",300);

// Recursively call the link() function again. Use setTimeOut() to set the delay because it takes time for the server to perform sql operations. When there is new information, it will be set on the server. When the read flag is 1 and has not been successful, AJAX may have sent multiple query messages, which will cause a message to be returned multiple times.

 

        }

 

    };

}

Implemented with jQuery plugin:

var link={  // Configuration object of jQuery 's AJAX execution

 

      type:"GET", // Set the request method, the default is GET ,

 

      async: true , // Set whether to be asynchronous, the default is asynchronous

 

      url:"customback.php",

 

      dataType:"json", // Set the expected return format, because the server returns json format, the data is treated as json format here

 

      success:function(msg){

 

            process...

 

            setTimeout("link()",300);

 

      } // Callback function when successful, process the returned data, and delay the establishment of a new request connection

 

}

 

$.ajax(link); // Execute the ajax request.


Program expansion:

Add send chat window:

Create a new function to process the POST request of ajax, use ajax to send the sender, the information sent each time, and the recipient to the server, and set up a separate PHP script to process the information and insert the information into the database.

It should be noted that when using JS to natively implement a POST request to send information, it is necessary to set the HTTP header of the ajax object to simulate the operation of form submission:

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Chat room message processing:

In order to prevent all information from being queried every time, we change the query operation of the database, set idflag=0, after each query, set idflag to the id of the queried data, we query the ID larger than idflag when querying , that is , the newly added information.

In this way, a simple chat room program is ready.

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325386166&siteId=291194637