Question thrown: How does a Web browser maintain communication with a service?
Method One: Ajax polling
Method Two: EventSource polling
Method Three: WebSocket Maintain long connection
The following solution is the combination of Ajax polling and EventSource polling.
Client code:
<!DOCTYPE HTML><HTML><Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title></title> <Scriptsrc= "Jquery.min.js"></Script> <Scriptsrc= "Pollsource.js"></Script></Head><Body> <H1>Server Data:</H1> <DivID= "Serverdata"></Div> <ahref= "Javascript:Poll.open (+);">Open poll</a> <ahref= "javascript:Poll.close ();">Close poll</a> <Scripttype= "Text/javascript"> varServerdata,poll; varServer_url= "index.php"; Window.onload= function() {serverdata=document.getElementById ("Serverdata"); Poll= NewPollsource (Server_url); Poll.onmessage= function(data) {//console.log (data);JSON=json.parse (data); Serverdata.innerhtml=Json.data; } } </Script></Body></HTML>
Pollsource.js Code:
/** * pollsource JavaScript Polling server * @param string URL server address Example: www.example.com/index.php * @param json Jsonparam passed to Server parameters * @author Echo*/functionPollsource (url,jsonparam) { This. url =URL; This. OnMessage =NULL; This. Resource =NULL; This. Polltype =typeof(EventSource) = = ' undefined '? ' Ajaxget ': ' EventSource '; //Pass the polling type to the server for the server to respond if(typeofJsonparam = = ' object ') {jsonparam[' Polltype '] = This. Polltype; }Else{Jsonparam= {Polltype: This. Polltype}; } This. url + = '? '; for(varIinchJsonparam) { This. url + = i+ ' = ' +jsonparam[i]+ ' & '; } This. url = This. url.substring (0, ( This. url.length-1)); /** * Start Polling * @param number spend ajaxget the speed unit is milliseconds*/ This. Open =function(spend) {varOnMessage = This. OnMessage; varURL = This. URL; if(typeofspend = = ' undefined ') spend = 5000; if( This. Polltype = = ' Ajaxget ') { //Use polling This. Resource = {}; This. Resource.lockint = SetInterval (function(){ Try{$.get (url,{},function(JSON) {if(typeofOnMessage = = ' function ') OnMessage (JSON); }); }Catch(e) {alert (e.message); }},spend); This. Resource.close =function() { if(typeof This. Lockint = = ' Number ') {clearinterval ( This. Lockint); } } }Else{ //using server to send event technology This. Resource =NewEventSource ( This. URL); This. Resource.onmessage =function(e) {if(typeofOnMessage = = ' function ') OnMessage (e.data); } This. Resource.onerror =function(e) {if( This. readyState = = 2) alert (' connection not established, or has been closed, or a fatal error has occurred '); } } } /** * Turn off polling*/ This. Close =function() { if( This. Resource) This. Resource.close (); }}
Service-Side code:
<?PHPHeader("content-type:text/html; Charset=utf-8 ");d Ate_default_timezone_set ("Asia/shanghai");$result=Array(' Code ' =>0, ' msg ' = ' pull success ', ' data ' = ' The current time is: '.Date(' y-m-d h:i:s '));$result= Json_encode ($result);$PollType=isset($_get[' Polltype ']) ?Trim($_get[' Polltype ']) : ‘‘;if($PollType= = ' Ajaxget ') { //header (' Content-type:application/json; Charset=utf-8 '); Echo $result;}Else if($PollType= = ' EventSource ') { Header(' Content-type:text/event-stream '); Echo' Data: '.$result." \ n "; Echo' retry:1000 '. " \ n ";//tell the client to initiate the request 1 seconds at a time Flush();}Else{ die(' ERROR ');}
Test results:
Code Download: Baidu Network disk
Reference resources:
Https://developer.mozilla.org/zh-CN/docs/Server-sent_events/EventSource
Https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events#Event_stream_format
JavaScript polling the request server