Method 1. Comet
Http://www.xiumu.org/technology/the-php-notes-comet-long-connection-instance.shtml This article is very good, Ajax keeps a long connection with the server, The server blocks until there is a new message, that is, the server needs to set the maximum run time to unlimited, the client's Ajax long-time connection until the server rents the plug is complete, and returns the result.
Browser-side
<meta content= "text/html; Charset=utf-8 "http-equiv=" Content-type "><title>comet test</title><script type=" Text/javascript "Src=" http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js "></script><script type=" Text/javascript " >(function($){ functionHandleresponse (response) {$ (' #content '). Append (' <div> ' + response[' msg ') + ' </div> '); } varTimestamp = 0; varurl = './chat_backend.php '; varNoError =true; varAjax; functionConnect () {Ajax= $.ajax (URL,{type: ' Get ',Data: {' timestamp ': timestamp},Success:function(transport) {Eval(' var response = ' +transport); Timestamp= response[' timestamp ']; Handleresponse (response); NoError=true; }, Complete:function(transport) {(!noerror) && SetTimeout (function() {Connect ()}, 5000) | |Connect (); NoError=false; } }); } functiondorequest (Request) {$. Ajax (URL,{type: ' Get ',Data: {' msg ':request}}); } $(' #cometForm '). Live (' Submit ',function() {dorequest ($ (' #word ').Val ()); $(' #word '). Val ('); return false; }); $ (document). Ready (function() {connect (); });}) (jQuery);</script><div id= "Content" ></div><div style= "margin:5px 0;" ><form action= "javascript:void (0);" id= "Cometform" method= "get" ><input id= "word" name= "word" type= "text" Value= "" ><input name= "Submit" type= "Submit" value= "Send" > </form></div>
Server-side
1<?PHP2 3 $filename=dirname(__file__).‘ /data.txt ';4 5 //messages are stored in this file.6 $msg=isset($_get[' msg ']) ?$_get[' msg ']: ';7 8 if($msg! = "){9 file_put_contents($filename,$msg);Ten die(); One } A - //keep looping until the file that stores the message is modified - $lastmodif=isset($_get[' timestamp ']) ?$_get[' timestamp ']: 0; the $currentmodif=Filemtime($filename); - while($currentmodif<=$lastmodif){//If the data file has been modified - Usleep(100000);//100ms pause to relieve CPU pressure - Clearstatcache();//Clearing Cache information + $currentmodif=Filemtime($filename); - } + A //returns a JSON array at $response=Array(); - $response[' msg '] =file_get_contents($filename); - $response[' timestamp '] =$currentmodif; - EchoJson_encode ($response); - Flush(); - in?>
Method 2. WebSocket
This is a high-end JS HTML library or class, you can establish a long connection with the server, the server can send the socket information, JS access to information, read and display.
Use Php+ajax to build a chat room app