Websockets can replace long-polling. This is an interesting concept; the client sends a request to the server – now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent – the client next receives this, and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long-polling isn’t really a piece of fancy technology: it’s also possible for a request to time-out, and thus a new connection will be needed anyway.
Many Ajax applications makes use of the above – this can often be attributed to poor resource utilization.
Wouldn’t it be great if the server could wake up one morning and send its data to clients who are willing to listen without some sort of pre established connection? Welcome to the world of PUSH technology!
This tutorial will focus more on the client building rather than server implementation.
Browse through the files and make changes where appropriate.
So in this code we’re creating a simple template: we have a box for the chat log, an input box, and one disconnect button.
Step 4: Add Some CSS
Nothing fancy, just space some elements out.
- 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;
- }
Step 5: WebSocket Events
First, let’s try and understand the idea of WebSocket events.
The Events
We’ll be using three events:
- onopen: When a socket has opened
- onmessage: When a message has been received
- onclose: When a socket has been closed
But how can we implement this?
First create a WebSocket object
- var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");
And checking for events is as simple as:
- socket.onopen = function(){
- alert("Socket has been opened!");
- }
But what about when we receive a message?
- socket.onmessage = function(msg){
- alert(msg);
- }
However, let’s avoid using alert boxes, and actually integrate what we’ve learned into the client page.
Step 6: JavaScript
Ok, so let’s get started. First we put our code in jQuery’s document ready function, then we check whether the user has a WebSockets-enabled browser. If they do not, we append a link to Chrome in the HTML.
- $(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="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
- }else{
-
-
-
- connect();
-
- function connect(){
-
-
- }
- });
As you can see, if the user has WebSockets then we call a connect() function. This is the core of the functionality: we’ll start with the open, close and receive events.
We’ll define the URL of our server
- var socket;
- var host = "ws://localhost:8000/socket/server/startDaemon.php";
Wait, where’s the http
in that URL? Oh right, it’s a WebSocket URL, so it’s using a different protocol. Here’s a breakdown of the pieces of our URL:
Let’s continue with our connect() function. We will put our code within a try/catch block; so if something goes wrong, we can let the user know. We create a new WebSocket, and pass the message to a message function which I’ll explain later. We create our onopen, onmessage and onclose functions. Note that we also show the user the socket status; this is not necessary, but I’m including it here as it can be helpful for 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 fairly simple, it takes in some text that we want to show the user and appends it to the chatLog. We create the appropriate class for paragraph tags in the socket event functions which is why there is only one closing paragraph tag in the message function.
- function message(msg){
- $('#chatLog').append(msg+'</p>');
- }
So Far…
If you’ve been following up to this point, well done! We’ve managed to create a basic HTML/CSS template, create and establish a WebSocket connection and keep the user updated as progress was made with the connection.
Step 7: Sending Data
Now rather than having a submit button, we can detect when the user presses return on their keyboard, and run the send function. The ’13′ you see below is the ASCII key for the enter button.
- $('#text').keypress(function(event) {
- if (event.keyCode == '13') {
- send();
- }
- });
And here’s 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("");
-
- }
Remember what you see above may be a chunky bit of code, but in reality, the code we really need is:
The extra code is doing a number of things: detecting if the user didn’t enter anything but still hit return, clearing the input box, and calling the message functions.
Step 8: Closing the Socket
Closing the socket is fairly straightforward: attach a click handler to our disconnect button and we’re done!
- $('#disconnect').click(function(){
- socket.close();
- });
The Completed JavaScript
- $(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="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
- }else{
-
-
- 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();
- });
-
- }
-
- }
-
- });
Step 9: Run the WebSocket Server
We will need command line access. Luckily, XAMPP has a handy shell option. Click ‘Shell’ on the XAMPP control panel, and type in:
php -q path\to\server.php
You have now started a WebSocket server!
Finished
When the page loads, a WebSocket connection will attempt to be established (try editing the code so the user has connect/disconnect option). Then, the user can enter messages and receive messages from the server.
That’s it!
Thanks for reading; I hope you enjoyed this tutorial! Remember, as exciting as WebSockets may be, things may change. You can refer here to keep up to date on the
W3C WebSocket API.