Start Using HTML5 WebSockets Today
Tutorial Details
- Topic: WebSockets
- Difficulty: Easy
- Estimated Completion Time: 1 Hour
One of the cool new features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we’ll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.
What are WebSockets?
WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. At the moment, it’s still being standardized by the W3C; however, the latest versions of Chrome and Safari have support for WebSockets.
What do WebSockets Replace?
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!
Step 1: Get the WebSocket Server
This tutorial will focus more on the client building rather than server implementation.
I’m using XAMPP on Windows 7 to run the PHP server locally. Grab a copy of phpwebsockets which is a WebSocket server in PHP. (Note: I experienced some problems with this version, I made some changes to it and will including it in the source files) There are various WebSocket implementations; if one doesn’t work, you can try another or just continue with the tutorial.
- jWebSocket (Java)
- web-socket-ruby (ruby)
- Socket IO-node (node.js)
Start the Apache server

Step 2: Change URLs and Ports
Change the server according to your setup, for example in setup.class.php:
public function __construct($host='localhost',$port=8000,$max=100)
{
$this->createSocket($host,$port);
}
Browse through the files and make changes where appropriate.
Step 3: Start Building the Client
Lets get a basic template up; 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">e.g. try 'hi', 'name', 'age', 'today'</p>
<input id="text" type="text" />
<button id="disconnect">Disconnect</button>
</div><!-- #container -->
</div>
</body>
</html>
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); //Awesome!
}
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{
//The user has WebSockets
connect();
function connect(){
//the connect function code is below
}
});
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:
socket.send(); //Thanks JavaScript
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{
//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: 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.







jQuery Lightbox Evolution only $12.00
Events Calendar Pro - Wordpr ... only $30.00 
This is awesome, thanks! I wonder how long it’ll take to have this become a feature that we can use more or less safely in projects.
Glad you like it!
Don’t know when it’ll be safe to use, could be some time.
There are some WebSocket implementations out there that provide a Flash fallback if WebSockets are not supported.
how can any one use that today when only chrome/safari support it ? are we targeting 10% of the population ?
It may not be suitable for web applications intended for a wide audience, but that doesn’t mean you can’t start using it now for personal projects.
I think some code out there allows a flash fallback to be used if WebSockets is not supported by the browser. http://github.com/gimite/web-socket-js
Firefox 4 will support websocket as well! It’s a very nice new feature with a lot of opportunities and it’s just a question of time that it will be available for every user which uses a modern browser (IE9 will support it too).
So that’s a good deal in my opinion. If you wanna use a modern webtechnic you have to use a modern browser.
and heaven forbid we use chromeframe. let’s be honest. this is targeted for web applications, which means you can call the shots on requirements. tell them to use a modern browser to use your application, or just include the chromeframe, and stop worrying about it. web apps are an entirely different game than standard websites.
Now that is a dang good tutorial. More of these levels of Tuts plz!!!!
Great tutorial! I’m reading HTML5 for Web Designers right now, and it’s leaving me wanting more technical details about the API’s and advanced “web app” features. This is great. More!!!!
What’s the best WebSocket server to use with MAMP?
I haven’t used MAMP, but try out PHP WebSockets http://code.google.com/p/phpwebsockets/ , the instructions in the tutorial should be fairly independent of the local server you’re running. But one thing you will need access to is the console/shell. (See step 9)
Thank you! Was looking for this for a long time… and is so simple to use!
Will try to use this in a large project to test the load
I think one of the best examples of this technology is Mr. Doob’s Multiuser Sketchpad but unfortunately it is currently down (due to bandwidth costs I believe) http://mrdoob.com/projects/multiuserpad/
This thing is huge Luke ! Excellent link.
Thanks a lot for this very nice and clean tutorial. Just tested it and it works like a charm!
Your welcome, good to hear it worked for you. Hope you can produce some interesting web apps!
Thanks amazing how much funcionality they have put into HTML5!
Great article by the way!
Keep up the GOOD work!
I can’t believe this, I no longer have to use node or other AJAX push technologies. Now I do not doubt HTML5.
Node is awesome!
Question: If I wanted to use this on a shared host, the host would have to have a Websocket server installed. So, are there any hosts that offer a Websocket server?
Best to use this on a server for which you have full access, I don’t know of any shared hosting that offers a WebSocket server to use.
I’ve heard of some people using Slicehost to host their WebSocket server http://www.slicehost.com/
Oh and just to clarify you would need to set up the server yourself…unless a hosting company out there does offer it as a pre-installed option – I am not aware of any.
I contacted Dreamhost a while ago about web sockets and they said they didn’t have any plans to install it on the shared service but I could buy a personal server if I wanted
I can’t believe that you are using Windows 7
doesn’t work in Google Chrome. I can’t get connected, it will stay in status 0.
but is works fine in Safari 5.0.
Hey
,
The phpwebsocket library is based on the version 0.75 of WebSocket protocol specification. It works with Chrome but not with Firefox which has upgraded to the 0.81. This version of the specification adds a security layer in the protocol. You can see it here: http://whatwg.org/specs/web-socket-protocol/.
So now, no library supports this last version of the WebSocket protocol specification actually, except if you use NodeJS with the WebSocket Gecko prototype.
Thank you for that information, http://www.whatwg.org/specs/web-socket-protocol/ is a long read but seems to contain lots of useful information.
Don’t you think WebSockets are not scalable? I am asking this because you mentioned above that a connection remains open.
“it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent”
It means while communicating with websockets, connection persistent. Am I right?
Because the connection stays open we eliminate the need for a “request-response”. E.g With some traditional techniques each response was the result of a request.
I think WebSockets can in fact be very scalable! (However I haven’t really tested this out)
This is a really nice article, thanks!
But I dont really get the goal of this technology? Why it should be used instead of AJAX?
Thank you.
To understand the technology better feel free to read the top of this page where it’s titled: What do WebSockets Replace?
Nice work! Look very easy!
Very very nice, once it will be more supported, the web-revolution will begin – games, apps, etc.
FF4 (currently only in beta) also supporting webSockets..
Has anyone actually gotten this work?
Thank you for sharing and that was a good resources for web designer
Web Sockets aren’t a part of HTML5. It’s sad to see that “HTML5″ has turned into a marketing word.
i definitely add this tech to my apps…
tnx..
For the HOST in Javascript.
You can simply use
var host = “ws://localhost:8000/”;
Dont write the complet path !
Thank you for sharing.
However, It doesn’t work in safari 5.0.
Socket Status : 0
Socket Status : 2 (Closed)
but is works fine in Chrome.
Socket Status : 0
Socket Status : 1 (Open)
* used XAMPP and 8080 ports
Have you tried to refresh your safari? Its works like a charm on my Safari 5.0. Or perhaps port 8080 you are using in websocket conflict with the port you are using for http?
@Umar, Thanks for this good tutorial, buddy.
Anyway, you got a tiny-little-bit oversight in Step 2. The file is needed to modify is socket.class.php, not setup.class.php. But after all, this is a very good article introducing websocket technology.
If you need an implementation of WebSocket that works on every browser, even those without Flash, try out http://socket.io
Hooray finally got it to work
Using xampp on vista.
Wouldn’t work in chrome latest nightly build (just said Socket Status: 0 and never got to 1), safari (disconnected straight away) or Firefox 4 beta (same problem as chrome nightly)
But it worked in Chrome Beta V5.0.375.125
Just in case anyone has the same problem, it’s probably the browser not the code / server.
Cheers, Tim
The issue with it working in chrome 5 and not chrome 6 can be read here: http://blog.chromium.org/2010/06/websocket-protocol-updated.html
Great tutorial!
im using Net_server pear extention http://pear.php.net/package/Net_Server/ for the server.
im asking if u can use th 80 port ?
thanks,
that’s really a nice one. thanks for this.
This tutorial is really very very helpful. I appreciate your efforts.
i can’t download the files