Ajax long polling _javascript tips for JavaScript and jquery for real-time web chat

Source: Internet
Author: User
Tags php server php script response code usleep

Introduced

As we all know, HTTP protocol is an object-oriented protocol belonging to the application layer, there are five characteristics of HTTP protocol:

1, support client/server mode;

2, simple and fast;

3, flexible;

4, no connection;

5, no State.

So once the request is a separate event, and there is no link before and after. So we have to solve the Web page real-time chat encountered a problem, how to ensure a long time contact with the server, so as to obtain information without a paragraph.

There are only so many ways in the past:

1, long connection, that is, server-side is not disconnected, PHP server with OB series functions to keep reading the output, but quite time-consuming server resources.

2, Flash Socket,flash AS3 language, create a socket server to process information.

3, polling, as the name implies is non-stop to send query messages, a new message immediately updated, but there will be many times useless requests.

4, long polling, is a polling upgrade version, the need for server-side coordination.

5, WEBSOCKET,HTML5 communication functions, the establishment of a server-side dedicated interface WS protocol to communicate, compatibility may become a problem.

This post summarizes the use of JS and JQ two ways (in fact, the difference is JS and JQ implementation), the implementation of long Ajax polling.

The thought of long polling:

If you send an inquiry with Ajax, the server enters the infinite wait when there is no information to return. Because of the asynchronous nature of Ajax, PHP executing the wait on the server side does not affect the normal processing of the page. Once the server queries to return information, the server returns 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 enters the wait when the server does not return information, reducing the number of empty replies from the normal polling server. It can be argued that long polling makes the server return more purposeful each time, rather than blindly returning.

Server-side implementation of long polling:

Chat Information Store:

The database is designed as information ID (msgid), Sender (sender), receiver (receiver), information content, set Senderread and Receiverread to mark whether the information has been read, read after the change of the mark, To distinguish whether the information has been read.

CREATE TABLE msg{

MsgId int not null primary key auto_increment,

sender char not NULL,

receiver Char (a) Not NULL, content

text,//message contents with text type, storage up to 65535 characters

Senderread tinyint enum (0,1) default 0,

receive Rread tinyint enum (0,1) default 0//Set a read flag tag

}

PHP Script:

The main purpose of the script is to handle each query from Ajax, AJAX query the database every time, to see if there is no new information, if not, just use the Usleep () function wait a second after the query again, until there is new information inserted into the database and was found, the script returned to the query to the data, and exit the Infinite Loop, End the script.

Set_time_limit (0)//Set script timeout is infinite, otherwise after the timeout time after the script will automatically shut down, polling failed.
 $link =new mysqli ("host", "User", "password", "database");
 $search = "Select Sender,receiver,content from msg where receiverread=0 limit 1";//Restrict reading one piece of data at a time to make it easy to modify its read flag
 $change = " Update chat set receiverread=1 where receiverread=0 limit 1 ";
 while (true) {//Enter an infinite loop
 $res = $link->query ($sql);//Query Results
  if ($res->num_rows!=0) {//Read information
  when there is unread information      $link->query ($change)//Set the read flag of the information to 1
  $msg = $res->fetch_assoc ();
  $jsonstr =json_encode ($msg);//Fetch the information, use the transcoding as JSON format, return to JS
  echo $jsonstr;
  break;//out the while loop after the output information, ending the current script
 }
 usleep (1000);//If no information will not enter the IF block, but will perform a wait 1 seconds to prevent PHP from looping to death.
 }

Client implementation:

The main task of the client is to set up an AJAX request function, which is invoked each time the query, when no information is returned, the server side is shelved, the current page is normally executed; when there is information returned, the function processes the returned data and quickly calls the function again to send a request.

With native JS:

function link () {
 var xhr=null;//first sets XHR to NULL, and calls functions again to xhr reuse for polling, causing errors
 xhr=new XMLHttpRequest ();
 Xhr.open (' Get ', ' serviceback.php ', true);//The third parameter must be set to true, asynchronous does not block, does not affect the subsequent JS execution.
 xhr.send ();
 Xhr.onreadystatechange=function () {
 if (xhr.readystate==4) {Strictly can also be used (xhr.readystate==4 && xhr.status = = 200 The server response code is limited to 200 when processing.
  if (xhr.responsetext!= ') {
   process ...//server-side return information, and the return information is not empty, the return information is processed.  
  }
  SetTimeout ("link ()");
Recursion calls the link () function again, settimeout () to set the delay because the server side of the SQL operation is time-consuming, when there is new information, when the server will be read Flag 1 is not successful, Ajax may have sent more than one query information, Causes a message to be returned multiple times. }}
 ;

Implemented with jquery Plug-ins:

The configuration object type of the Ajax execution of Var link={//jquery
  : "Get",//Set request mode, default to get,
  async:true,//set asynchronous, default to asynchronous
  ur L: "customback.php",
  dataType: "JSON",//Set the desired return format, as the server returns JSON format, where the data is treated as JSON format
  success:function (msg) {  
   process ...
   SetTimeout ("link ()", +);
  }          A successful callback function, processing the return data, and delaying the creation of a new request connection
}
$.ajax (link); Execute an AJAX request.
]

Program Expansion:

Add Send Chat window:

Create a new function to handle AJAX post requests, using AJAX to send the sender, each message sent to the server side, and set up a separate PHP script processing information to insert the information into the database.

It should be noted that the use of JS native implementation POST request to send information, to set the HTTP headers of Ajax objects, simulate the operation of the form submission:

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

Chat Room Message Processing:

In order to prevent every time to query all the information, we have to the database query operation change, set idflag=0, each query, set Idflag for the query to the ID of the data, query when we query than Idflag larger ID, that is, the new added information.

Well, this is the end of this article, using the sample code of this article a simple chat room program is done, the interest can be quickly put into practice.

Related Article

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.