A cool new feature in HTML5 is WebSockets, which allows us to talk to the server without AJAX requests. Today, BinGo will allow everyone to run WebSocket through the server side of the Php environment, create clients, and send and receive server-side information through the WebSockets protocol.
What are WebSockets?
WebSockets is a technology that performs bidirectional communication on a (TCP) interface, and a 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 have already supported 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 the data that has not been prepared. It will keep the connection open until the latest data is ready to be sent. After that, the client receives the data and then sends another request. . This has its benefits: reduce latency on either connection, and does not need to create another new connection when one connection is already open. But Long-Polling is not a fancy technique, and it is still possible that request pauses will occur, so a new connection will be required.
Some AJAX applications use the above-mentioned technology - which is often attributed to low resource utilization.
Just imagine how great it would be if the server would start up and send data to clients who would like to receive 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 execution.
I use XAMPP based on Windows 7 to implement running PHP locally. phpwebsockets is a PHP WebSocket server. (In my experience, there are some minor problems with this version. I have made some modifications to it and uploaded the source file to share with you.) The following different versions can also implement WebSocket. If one cannot be used, you can try other versions. Or continue reading the tutorial below.
jWebSocket (Java)
web-socket-ruby (ruby)
Socket IO-node (node.js)
Start the Apache server
Step 2: Modify URLs and ports
According to your previous installation, modify the server, the following is an example in 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 a client
Here 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 have created the basic template: a chat log container, an input input box and a disconnected button.
Step 4: Add some CSS
There is no fancy code, just deal with the style of the tag.
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 a 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 the message:
socket.onmessage = function(msg){ alert(msg); //Awesome! } |
But we still try to avoid using alert, and now we can integrate what we have learned into the client page.
Step 6: JavaScript
First, we put the code into the document.ready function of jQuery, and then we also need to check whether the user's browser supports WebSocket. If it is not supported, we will add a link to the Chrome browser 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 function, 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 out why there is no http in the URL? Well, yes, this is a WebSocket URL that uses a different protocol.
Let's continue to complete the connect() function below. We put the code into the 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, and we will explain it later. We create our onopen, onmessage, and onclose functions. It should be noted that we provide the user with port status, which is not necessary, but we put it in mainly 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, it fills the text we want to present to the user into the chat log container. We create the appropriate class for the paragraph (<p>) tag in the socket event function, and we only have one paragraph end tag in the message function.
function message(msg){ $('#chatLog').append(msg+'</p>'); } |
Current results
If you have followed the tutorial above step by step, it's great, we have created HTML/CSS templates, created and established Websocket connections, and kept the user progress updated by creating connections.
Step 7: Send data
Now we have the submit button, but we still need to listen to the user pressing the keyboard event 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(""); } |
Here we need:
socket.send();
The extra code does the following work: detect whether the user has entered nothing but clicked back, clear the input input box, and execute the message() function.
Step 8: Close Socket
The operation to close Socket is quite simple, just add a click event to the disconnect button to listen.
$('#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: When running the WebSocket server, we need to enter some command lines. XAMPP provides relatively convenient shell options. Click the "shell" button in the XAMPP control panel and enter:
php -q pathtoserver.php |
Now you have the WebSocket server running!
The mission is done!
When the page is read, an attempt will be made to create a WebSocket connection, and the user can then enter the information and receive it from the server. Thank you for your patience in reading this tutorial. I hope you can learn useful knowledge from it. HTML5 WebSocket is really exciting! You can learn about the latest developments in HTML5 WebSocket through The WebSocket API.