WebSocket is the technology that is generated to address real-time communication between the client and the server.
Introduce what it is nonsense not to say more, directly say how to use:
Client:
1. Create a EventSource object
var es = New EventSource (URL)
Where the URL parameter is required to pass in a background file address that needs to establish communication
2. Specifying event callbacks
An instance of EventSource can specify the following three event callbacks:
(1). OnOpen: Connection established successfully
es.onopen=function(e) { // The content executed after a successful connection is established }
(2). OnMessage: Receive Data
es.onmessage=function(e) { // receive data after receiving the content. E.data is the received data Console.log (e.data) }
(3). OnError: Connection Failed
es.onopen=function(e) { // Connection Setup failed to execute content }
Server-side:
Setting the response header: Content-type:text/event-stream
Here's a simple chestnut, The server side sends the current time to the client per second:
Index.html:
<!DOCTYPE HTML><HTML><Head> <title></title> <MetaCharSet= "Utf-8"> <Scripttype= "Text/javascript"src= "Script.js"></Script></Head><Body> <DivID= "ZT"></Div> <H3>Current time:</H3> <DivID= "Date"></Div></Body></HTML>
<div id= "ZT" ></div> to store connection status
<div id= "date" ></div> to hold the current time
Script.js:
(function(){ varstatus,date; varServerURL = ' socket.php '; Window.onload=function() {Status= document.getElementById (' ZT ')); Date= document.getElementById (' Date '); Connect (); }; functionConnect () {status.innerhtml= ' Creating connection '; varES =NewEventSource (ServerURL); Es.onopen=Opencallback; Es.onerror=Errorcallback; Es.onmessage=Messagecallback; } functionOpencallback (e) {status.innerhtml= ' Connected ' } functionErrorcallback (e) {status.innerhtml= ' connection error ' } functionMessagecallback (e) {date.innerhtml=E.data}}) ();
Description
Creates a EventSource object, passing in socket.php as a parameter. socket.php is the background file that establishes the communication.
Perform OnOpen callbacks, OnMessage callbacks, onerror callbacks, and display the corresponding connection status and received data in the page.
socket.php:
<? php header (' content-type:text/ Event-stream ' for ( $i = 0; $i <10; $i ++) {Date_default_timezone_set ( " Asia/shanghai "); echo ' data: '. date (' y-m-d h-i-s ' ); echo "\ n" ob_flush (); @flush (); sleep (1?
Set the response header Content-type to Text/event-stream
The current time is sent every second.
This creates one of the simplest websocket applications.
Source Address: Https://github.com/OOP-Code-Bunny/html5/tree/master/websocket
Html5-websocket Technical Learning (1)