One of the cool new features in HTML5 is WebSockets, which allow us to talk to the server without AJAX requests. Today Bin Go will let you run WebSocket through the server side of the Php environment, create a client and send and receive server-side information through the WebSockets protocol.
What are WebSockets?
WebSockets is a technology for two-way communication on a (TCP) interface, PUSH technology type. At the same time, WebSockets will still be based on the W3C standard. So far, the latest versions of Chrome and Safari browsers already support WebSockets.
What will WebSockets replace? WebSockets can replace Long Polling (PHP server push technology), which is an interesting concept. The client sends a request to the server. Now, the server will not respond to data that is not ready. It will keep the connection open until the latest data is ready to be sent. After that, the client receives the data and sends another request. . This has its benefits: it reduces latency on either connection and eliminates the need to create a new connection when one is already open. But Long-Polling is not a fancy technology. It is still possible that request suspension will occur, so a new connection will need to be established.
Some AJAX applications use the above techniques - this is often attributed to low resource utilization.
Just imagine, what a great thing it would be if the server would start itself up in the morning and send data to clients that want to receive it without having to set up some connection ports in advance! Welcome to the world of PUSH technology!
Step 1: Get the WebSocket server
This tutorial will focus more on client creation rather than server-side execution and other operations.
I'm using XAMPP on Windows 7 to run PHP locally. phpwebsockets is a PHP WebSocket server. (In my experience, this version has some minor problems. I have made some modifications to it and uploaded the source files to share with everyone) The different versions below can also implement WebSocket. If one does not work, you can try other versions. Or continue with the tutorial below.
jWebSocket (Java)
web-socket-ruby (ruby)
Socket IO-node (node.js)
Start the Apache server
Step 2: Modify URLs and ports
Modify the server based on your previous installation. Here is an example from setup.class.php:
public function __construct($host='localhost',$port=8000,$max=100) { $this->createSocket($host,$port); } |
Browse the file and make changes if appropriate.
Step 3: Start creating the client
Let's create the basic template. This is my client.php file:
<!DOCTYPE html> <html> <head> <script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <title>WebSockets Client</title> </head> <body> <div id="wrapper"> <div id="container"> <h1>WebSockets Client</h1> <div id="chatLog"> </div><!-- #chatLog --> <p id="examples">eg try 'hi', 'name', 'age', 'today'</p> <input id="text" type="text" /> <button id="disconnect">Disconnect</button> </div><!-- #container --> </div> </body> </html> |
We've created the basic template: a chat log container, an input box, and a disconnect button.
Step 4: Add some CSS
There is no fancy code, just handle the label style.
body { |
Step 5: WebSocket
Events First let us try and understand the concept of WebSocket events:
WebSocket events:
We will use three WebSocket events:
onopen: When the interface is opened
onmessage: When a message is received
onclose: When the interface is closed
How do we achieve this?
First create the WebSocket object
var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");
Then detect the event as follows
socket.onopen = function(){ alert("Socket has been opened!"); } |
Do this when we receive information:
socket.onmessage = function(msg){ alert(msg); //Awesome! } |
But we still try to avoid using alert, and now we can integrate what we learned into the client page.
Step 6: JavaScript
First we put the code into jQuery 's document.ready function, and then we also check whether the user's browser supports WebSocket. If it's not supported, we'll add a link to the Chrome page.
$(document).ready(function() { if(!("WebSocket" in window)){ $('#chatLog, input, button, #examples').fadeOut("fast"); $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="Google'>http://www.google.com/chrome">Google Chrome</a>?</p >').appendTo('#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 functionality, we will 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, this is a WebSocket URL, using a different protocol.
Let's continue with the connect() function. We put the code into a try/catch block so that if there is a problem with the code, we can let the user know. We create a WebSocket and pass the information to the message() function, which will be explained later. We create our onopen, onmessage and onclose functions. It should be noted that we provide the port status for the user. This is not required, but we put it in mainly to facilitate 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 very simple, it fills the chat log container with 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 only have a paragraph closing tag in the message function.
function message(msg){ $('#chatLog').append(msg+'</p>'); } |
Current results
If you have followed the above tutorial step by step, great, we have created the HTML/CSS template, created and established the Websocket connection, and kept the user's progress updated by creating the connection.
Step 7: Send data
Now we have a submit button, but we also need to monitor the event when the user presses the keyboard and run the send function. The '13' below is the ASCII code corresponding to the Enter key.
$('#text').keypress(function(event) { if (event.keyCode == '13') { 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:
socket.send();
The extra code does the following: detects whether the user clicks return after entering nothing, clears the input box, and executes the message() function.
Step 8: Close Socket
Closing the Socket is quite simple, just add a click event listener for the disconnect button.
$('#disconnect').click(function(){ socket.close(); }); |
Complete JavaScript code
$(document).ready(function() { if(!("WebSocket" in window)){ $('#chatLog, input, button, #examples').fadeOut("fast"); $('<p>Oh no, you need a browser that supports WebSockets. How about <a href=" Google'>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+' (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); } 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 == '13') { send(); } }); $('#disconnect').click(function(){ socket.close(); }); }//End connect }//End else }); |
Step 9: We need to enter some command lines to run the WebSocket server. XAMPP provides more convenient shell options. Click on the 'shell' button of the XAMPP control panel and enter:
php -q pathtoserver.php |
Now you have a WebSocket server running!
You're done!
When the page is read, an attempt is made to create a WebSocket connection, and the user can then enter information and receive information from the server. Thank you for your patience in reading this tutorial. I hope you learned useful knowledge from it. HTML5 WebSocket is indeed exciting! You can learn about the latest developments of HTML5 WebSocket through The WebSocket API .