Summary: A cool new feature in HTML5 is WebSockets, which allows us to talk to the server without requiring an AJAX request. Today, go will let you run WebSocket from the server side of the PHP environment, create the client and send and receive server-side information via the WebSockets protocol.
What is WebSockets?
WebSockets is the technology of the two-way communication on a (TCP) interface, the push technology type. At the same time WebSockets will still be based on the web standards, so far, Chrome and Safari's latest version of the browser has supported WebSockets.
What will websockets replace?
WebSockets can replace long Polling (PHP service-side push technology), which is an interesting concept. The client sends a request to the server, and now the server does not respond to data that is not yet ready, it keeps the connection open until the latest data is ready to be sent, and then the client receives the data and then sends another request. This has the benefit of reducing the latency of any connection, and you do not need to create another new connection when a connection is already open. But long-polling is not a fancy technique, and it is still possible for a request to pause, so a new connection will need to be established.
Some AJAX applications use the above techniques-this is often attributed to low resource utilization.
Imagine, if the server will start in the morning and send the data to those who want to receive without the early establishment of some connection port client, this is a wonderful thing ah! Welcome to the world of push technology!
Step one: Fix WebSocket server
This tutorial will focus more on client creation than server-side execution.
I use Windows 7-based XAMPP to run PHP locally. Phpwebsockets is a PHP websocket server. (In my experience this version has some minor problems, I have made some changes to it and upload the source file share to everyone) these different versions can also be implemented WebSocket, if one is not available, you can try other versions or continue to see the following tutorial.
Start Apache Server
Step two: Modify URLs and ports
To modify the server based on your previous installation, here are the examples in setup.class.php:
Publicfunction _construct ($host = ' localhost ', $port =8000, $max =100) { $this->createsocket ($host, $port); }
Browse the file and make changes where appropriate.
Step three: Start creating the Client
Below to create the basic template, this is my client.php file:
<! DOCTYPE html>
We've created a basic template: A chat log container, an Input entry box, and a disconnected button.
Fourth step: Add some CSS
No fancy code, just dealing with the style of the label.
Body { font-family:arial, Helvetica, Sans-serif;} #container { border:5px solid grey; width:800px; margin:0 Auto; padding:10px;} #chatLog { padding:5px; BORDER:1PX solid black;} #chatLog p { margin:0;}. Event { color: #999;}. warning{ Font-weight:bold; Color: #CCC;}
Fifth Step: WebSocket Event
First let's try and understand the concept of the WebSocket event:
WebSocket Event:
We will use three WebSocket events:
- OnOpen: When the interface is open
- OnMessage: When a message is received
- OnClose: When the interface is closed
How do we do that?
First create the WebSocket object
var socket =new WebSocket ("ws://localhost:8000/socket/server/startdaemon.php");
Then detect the event as follows
Socket.onmessage =function (msg) { alert (msg);//awesome! }
But we try to avoid using alert, and now we can integrate what we've learned into the client page.
Sixth step: JavaScript
First we put the code in the jquery document.ready function, and then we also check whether the user's browser supports WebSocket. If not, we'll add a link to the Chrome browser page.
$ (document). Ready (function () { if (! () WebSocket "in window)" { $ (' #chatLog, Input, button, #examples '). FadeOut ("fast"); $ (' <p>oh No, need a browser that supports WebSockets. How about <a href= "Http://www.google.com/chrome" >google chrome</a>?</p> '). Ppendto (' #container '); } else{ //the user has WebSockets connect (); function Connect () { //the connect function code is below } });
As you can see, if the user's browser supports WebSocket, we will execute the Connect () function. Here is the core feature, and we'll start creating open, close, and receive events.
We will define the URL on our server.
var socket; var host = "ws://localhost:8000/socket/server/startdaemon.php";
You may find that there is no HTTP in the URL? Well, yes, it's a websocket URL that uses a different protocol. Here is the URL decomposition diagram:
Let's continue with the Connect () function, where we put the code into the Try/catch block, so we can let the user know if there is a problem with the code. We create the WebSocket and pass the information to the message () function, which is then explained. We create our OnOpen, onmessage, and OnClose functions. It is important to note that we provide the user with the port status, which is not required, but we put it in the main for the convenience of debugging.
- connecting = 0
- OPEN = 1
- CLOSED = 2
function Connect () { try{ var socket; var host = "ws://localhost:8000/socket/server/startdaemon.php"; var socket =new WebSocket (host); Message (' <p class= ' event ' >socket Status: ' +socket.readystate '); Socket.onopen =function () { message (' <p class= ' event ' >socket Status: ' +socket.readystate+ ' (Open) '); } Socket.onmessage =function (msg) { message (' <p class= ' message ' >received: ' +msg.data '); } Socket.onclose =function () { message (' <p class= ' event ' >socket Status: ' +socket.readystate+ ' (Closed) '); } } catch (Exception) { message (' <p>error ' +exception); } }
The message () function is simple, and it fills in the chat log container The text we want to display to the user. We create the appropriate class for the paragraph (<p>) tag in the socket event function, and we have only one paragraph end tag in the message function.
Function Message (msg) { $ (' #chatLog '). Append (msg+ ' </p> '); }
The current results
If you've done it step by step in the tutorial above, well, we've created the Html/css template, created and established a websocket connection, and kept the user's progress updated by creating a connection.
Seventh Step: Send data
Now that we have the submit button, we also need to listen to the user press the keyboard event and run the Send function, and the following ' 13′ is the ASCII code for the ENTER key.
$ (' #text '). KeyPress (function (event) { if (Event.keycode = = ') { send (); } });
Here is the Send () function:
function Send () { var text = $ (' #text '). Val (); if (text== "") { message (' <p class= "Warning" >please enter a message '); return; } try{ socket.send (text); Message (' <p class= ' event ' >sent: ' +text ' } catch (Exception) { message (' <p class= ' warning ' > Error: ' + exception); } $ (' #text '). Val (""); }
Below we need to:
1socket.send ();The extra code does the following: Detects if the user has entered nothing but still clicks back, empties the input box, and executes the message () function.
Close socket
Closing the socket operation is fairly straightforward, and adding the Click event Listener for the Disconnect button is OK.
$ (' #disconnect '). Click (function () { socket.close (); });
Full JavaScript code
$ (document). Ready (function () {if (! () WebSocket "in window)" {$ (' #chatLog, Input, button, #examples '). FadeOut ("fast"); $ (' <p>oh No, need a browser that supports WebSockets. How about <a href= "Http://www.google.com/chrome" >google chrome</a>?</p> '). AppendTo (' #container ') ; }else{//the user has WebSockets connect (); function connect () {var socket; var host = "ws://localhost:8000/socket/server/startdaemon.php"; try{var socket =new WebSocket (host); Message (' <p class= ' event ' >socket Status: ' +socket.readystate '); Socket.onopen =function () {message (' <p class= ' event ' >socket Status: ' +socket.readystate+ ' (op EN) '); } socket.onmessage =function (msg) {message (' <p class= ' message ' >received: ' +msg.data); } socket.onclose =function () {message (' <p class= ' event ' >socket Status: ' +s Ocket.readystate+ ' (Closed) '); }} catch (Exception) {message (' <p>error ' +exception); } function Send () {var text = $ (' #text '). Val (); if (text== "") {message (' <p class= "Warning" >please enter a message '); return; } try{socket.send (text); Message (' <p class= ' event ' >sent: ' +text '} catch (Exception) {message (' <p class= "Warning" > "); } $ (' #text '). Val (""); } function Message (msg) {$ (' #chatLog '). Append (msg+ ' </p> '); } $ (' #texT '). KeyPress (function (event) {if (Event.keycode = = ') {send (); } }); $ (' #disconnect '). Click (function () {socket.close (); }); }//end connect}//end else});Nineth Step: Run the WebSocket server
To enter some command lines, XAMPP provides a more convenient shell option. Click the ' Shell ' button in the Xampp Control Panel and enter: Php-q path\to\server.php Now you have run the WebSocket server!
Done!
When the page is read, an attempt is made to create a websocket connection, and then the user can enter information and receive information from the server.
Thank you for your patience to read this tutorial, I hope you can learn from the useful knowledge, HTML5 websocket really exciting! You can learn about the latest developments in HTML5 WebSocket through the WebSocket API. Click here to download the source file
Article Source: HTML5 WebSockets Basic use sharing
HTML5 WebSockets Basic use sharing