# Start Using HTML5 WebSockets Today

##### Tutorial Details
• Topic: WebSockets
• Difficulty: Easy
• Estimated Completion Time: 1 Hour

One of the coolest 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.

## 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>

<title>WebSockets Client</title>

<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;
}
#chatLog{
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(){
}

socket.onmessage = function(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{ //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==""){
return ;
}
try{
socket.send(text);
message('<p class="event">Sent: '+text)
} catch(exception){
message('<p class="warning"> Error:' + exception);
}

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==""){
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.

Tags: html5
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
• http://nicolasrosental.com Nic Rosental

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.

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.

• http://www.level09.com level09

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

• http://www.avey.de Way

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.

• http://drewcovi.com Drew

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.

• http://dropletweet.com Siriquelle

Learn this now so that in 12 months, when support is more widespread you can use it in commercial projects and you wont be playing catch up. Also, its exciting playing around with HTML5 stuff, so much potential.

• Eric

Now that is a dang good tutorial. More of these levels of Tuts plz!!!!

• http://jacobdubail.com Jacob

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)

• Ricardo Verhaeg

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

• http://www.lkc-designs.com Luke

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/

• http://www.pauletienney.fr Paul

This thing is huge Luke ! Excellent link.

• http://www.avey.de Way

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!

• http://misto.dk Mikkel

Thanks amazing how much funcionality they have put into HTML5!
Great article by the way! :-)

Keep up the GOOD work!

• Darren L.

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!

• http://brianswebdesign.com Brian Temecula

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.

• http://www.csskarma.com Tim Wright

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

• Tom

I can’t believe that you are using Windows 7

• http://www.leonzhang.com hileon

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.

• http://hoa-project.net Ivan Enderlin

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.

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)

• http://beletsky.net Alexander Beletsky

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?

• http://www.dennsia.com dennso

Nice work! Look very easy!

• Gregg

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..

• Rick

Has anyone actually gotten this work?

• http://www.bizmedical.com bizmedical

Thank you for sharing and that was a good resources for web designer

• Bob

Web Sockets aren’t a part of HTML5. It’s sad to see that “HTML5″ has turned into a marketing word.

• paulon

i definitely add this tech to my apps… :D

tnx..

• http://www.wixiweb.fr Arnaud Lemercier

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

• http://gandamanurung.com ganda

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. :)

• Guillermo Rauch

If you need an implementation of WebSocket that works on every browser, even those without Flash, try out http://socket.io

• Tim

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

• David

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

• http://www.dz-tchat.com algerianTic

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,

• http://www.parasjairath.co.cc CCNA CCNP CCSP CCIE Dumps

that’s really a nice one. thanks for this.

• http://www.parasjairath.co.cc sidd

• karthic

• Beast Winterwolf

big problem! :( please, answer, this example works ONLY on localhost ??? when I change:

$WebSocket = new socketWebSocket(‘localhost’,8000); to$WebSocket = new socketWebSocket(’92.122.172.32′,8000);

in startDaemon.php, all works good, BUT when I change:

var host = ‘ws://localhost:8000/socket/server/startDaemon.php’;
to
var host = ‘ws://92.122.172.32:8000/socket/server/startDaemon.php’;

• http://www.codeforest.net/ Codeforest

Really nice tutorial.

But couldn’t we just use socket extension in PHP to create our own socket server and client ?

And that would work in all browsers.

• Joaquín Gatica

Awesome! Congratulations for the tut!

Hope this new technology is soon standardized.
Doesn’t work on Firefox 4 Beta 6, nor in Google Chrome 6, nor in Safari 5; at least for me. Can’t wait to develop some personal apps based on WebSockets. I’m planning to implement JSON.

I coded a small batch (named it “WebSockets.bat”) file that executes the necessary apps to run the WebSockets.

cd C:\wamp
start wampmanager.exe
cd C:\wamp\bin\php\php5.3.0
php -q ..\..\..\www\socket\server\startDaemon.php

My Chrome portable is located in “C:\GoogleChromePortable” and I’m using WAMP and that’s the explanation for the two final lines.
Hope it’s useful.
Regards

• Alfonso Garza

Great tutorial!!

I managed to get it working but then I tried to make a mysql connection on the Trigger.class.php file and I kept getting an error 2002. I am really not that good at PHP, but I thought that error was thrown when there was a permissions issue..

Any ideas why I get this error?

• alien

Hi, my php is running on IIS. How should i start the server? I failed to do so by entering the command shown above.

• Markus

Here is a wonderful example of websockets use in a productive environment:
http://www.jandaya.de

• http://hoa-project.net Ivan Enderlin

A few weeks ago, I wrote a library for a demo. It works with the draft -0.73 (the latest Websocket draft). You can read the code here: , that is not yet documented except the API.
An exemple? Sure.

This code is developed in Hoa (http://hoa-project.net), an open-source & free PHP5 framework —anyway. It proposes an unified and strong stream system among other things. Here, we have on the top Hoa_Stream that is the parent of Hoa_Socket that is the parent of Hoa_Websocket. The goal here is to extend Hoa_Websocket_Server to make a chat (i.e. receive all messages and send them to all connected persons). Easy: class Chat extends Hoa_Websocket_Server {

protected function compute ( $sourceNode,$message ) {

$id =$sourceNode->getId();
$nodes =$this->getNodes();
$count = count($nodes);

foreach($nodes as$i => $node) if(true ===$node->isFirstMessage()) {

$this->send($node, $count . ‘;’ .$message);
$node->setFirst(false); } elseif($node->getId() != $id)$this->send($node,$count . ‘;’ . $message); return; } } Here is two video demos (in french): http://j.mp/websocket_w (in WebM), http://j.mp/websocket_m (in MOV). What is it interesting here? The handshake of course. http://j.mp/aAdmZb at line 117, you can have the handshake code that supports the security layer introduced by the last draft. A demo was made with Firefox4b7+, Opera nightly, Chrome 6.4+, Webkit nightly, Safari 5.0.1+ and Chromium. Hope it can help :-). • Chris Great Tutorial! But you missed a closing character in Step 6:$(document).ready(function() {

if(!(“WebSocket” in window)){
$(‘#chatLog, input, button, #examples’).fadeOut(“fast”);$(‘Oh no, you need a browser that supports WebSockets. How about Google Chrome?’).appendTo(‘#container’);
} else {

//The user has WebSockets

connect();

function connect(){
//the connect function code is below
}
}
});

• axeff

Hi there,
great tutorial. But I can’t get it to work though.
In Safari (Version 5.0.2 on Mac) it right away closes the connection -> state 2.
In Chrome (7.0.517.44 on Mac) it stays in state 0.

Do I actually need to run the apache? Cause when I run the demon in terminal it tells me:
(CHROME VERSION)

2010-11-15 16:52:29 WebSocket: Resource id #8 CONNECTED!
2010-11-15 16:52:29 WebSocket: Requesting handshake…
2010-11-15 16:52:29 WebSocket: Handshaking…
2010-11-15 16:52:29 WebSocket: Done handshaking…

(SAFARI VERSION)

2010-11-15 16:55:28 WebSocket: Resource id #9 CONNECTED!
2010-11-15 16:55:28 WebSocket: Requesting handshake…
2010-11-15 16:55:28 WebSocket: Handshaking…
2010-11-15 16:55:28 WebSocket: Done handshaking…
2010-11-15 16:55:28 WebSocket: Resource id #9 disconnected!

so it does some kind of communication. but i won’t get the State 1 in any Browser…
any ideas on this?

• http://flax.ie/ Ciarán

I have the same problem, although only tested it in chrome, same version.

• http://gfeng.org small2

me too in chrome

• Marco

me too, does anyone have a solution?

• Jaywalking101

Also having the same problem. But, as someone else here already said, the original code from phpwebsocket at google code seems to work with latest chrome (I’m running Chrome 9). Another but though, right now it only works with one connection. (it’s weird) I suppose that I will be able to mix both codes and then have a full working version…

• Inavac

I have the same problem…!! in chrome and safari…. who can help us????

• Jaywalking101

I’m looking for a solution right now. I will be glad to help if I were succeded. (just replied to @Ciarán comment about it)

Hi, is websockets able to use IRC protocol like connecting to irc://eu.undernet.org. Instead of ws://….. ?

• http://www.designstudio16.com saurabh shah

Nice tutorial …

• geekforever

Nice tutorial.
But how can we make it work on the latest Chrome version ?

• http://pusherapp.com Damien Tanner

Brilliant tutorial. You might also find it interesting to try out a hosted websockets solution. Ours is called http://pusherapp.com :)

• Ming

I’ve tried this also but seems not working on Chrome(8.0.552.224).
But it works correctly for the source code in http://code.google.com/p/phpwebsocket/
The source code looks similar.

• A. Shore

Two questions really, both based on attempting to use websockets in a real-time environment.

1. Re starting the daemon; Say I’m using an ISP, and won’t have access to the command line. (Can anyone correct that?)

How can I accomplish that in script-land? Is has to be script-able somehow, no?

In my particular case, the application is ours, and we have a database available,- if that cd play a role somehow.

2. I’ll need the server to be able to initiate client-side actions, occasionally. Presumably, that’s via some callback function, possible a long-lived one. Feasible?

Thanks for any help here. I’ve been waiting for Websockets a looong time now, and I hope its time has arrived.

• http://monkey-house.ca Greg

My kingdom for a simple-to-run Websocket server for a LAMP stack. Found this article because it refers to a PHP implementation, but alas the link does not work.

• http://HANGDEP.COM MANH SOI

Setting environment for using XAMPP for Windows.

lamt@LAMT-PC C:\xampp
# php -q htdocs\websocket\server\startDaemon.php
2011-01-10 10:32:32 System: Socket Resource id #7 created.

Warning: socket_bind(): unable to bind address [0]: An attempt was made to acces
s a socket in a way forbidden by its access permissions.
in C:\xampp\htdocs\websocket\server\socket.class.php on line 48
2011-01-10 10:32:32 System: Socket bound to localhost:80.

Warning: socket_listen(): unable to listen on socket [0]: An invalid argument wa
s supplied.
in C:\xampp\htdocs\websocket\server\socket.class.php on line 55
2011-01-10 10:32:32 System: Start listening on Socket.

Hello friend, the server starts a lot more when I try to send a message nothing happens, you know why?

if you type a message and hit enter
not send to the server.

he recognizes when someone enters the page you know if the error is in the script?

image the error: http://img51.imageshack.us/i/22345.gif/

• Facelspa

Hey guys, somewhy, this doesnt work for me, i did every of these steps. I used a .bat program to start the websocket server, and heres what i get:

PHP Fatal error: Call to undefined function socket_create() in C:\wamp\www\sock
et\server\socket.class.php on line 38

Fatal error: Call to undefined function socket_create() in C:\wamp\www\socket\se
rver\socket.class.php on line 38
Press any key to continue . . .

The code of the .bat websocket starter:

@echo off
cd C:\wamp
start wampmanager.exe
cd C:\wamp\bin\php\php5.3.3
php -q C:\wamp\www\socket\server\startDaemon.php
pause

Any ideas guys?

• Jamie

Exact same prob with wamp. Loge some help…

• http://www.workshoplatino.com alekz

hi, you found the solution to the problem with the 38 line of code?

• Ryan Ewen

Anyone know how to update the handshake so that it is compatible with the newer spec? It needs the hash in there somehow I guess..

• Ryan Ewen

I should also mention that this is what needs to be done to get it working in Chrome 6+, etc (I think).