T S
                                KE
                               C eb
                             O W
                          S me
                         B -ti
                        E al
                       W he re                                   Ro
                                                                   bH
                                                                     aw
                                                                       kes



                     g t
                  cin
               bra
             Em
Hi, I’m Rob Hawkes and I’m here tonight to talk a little about WebSockets and why they’re
amazing.
If you don’t already know, I work at Mozilla.

My official job title is Technical Evangelist, but I prefer Rawket Scientist, which is what it says
on my business card.

Part of my job is to engage with developers like you and me about cool new technologies on
the Web.
Created by Phil Banks (@emirpprime)


Aside from that I spend most of my time experimenting with HTML5 and other cool
technologies.

If you’ve met me before then you probably already know about my slight addiction to canvas
and visual programming.

It’s fun!
Unfortunately I’m still in jet-lag mode at the moment. I flew back on Saturday after spending
a week in the US with Mozilla and talking about HTML5 gaming.

On Saturday night I slept a total of 2 hours, and last night I managed to squeeze in a good 7.

So I apologise in advance if we find that having 9 hours of sleep in the past 60 turns me in a
gibbering wreck.
ts ?
                                            e
                                          ck ugs
                                        So
                                     e b     ith
                                                 pl
                                   W to do  w
                                are hing
                             at      ot
                           Wh       N




Who already knows what WebSockets are?

Bi-directional communication, created by upgrading a standard HTTP connection.

Allows for data to be sent back and forth at the same time and without having to request it.

To clarify; once a WebSockets connection is made, data is pushed across it without either side
having to ask for it.
ts  ?
                                              e
                                            ck ool
                                        S o
                                      eb       retty
                                                     c

                                   e W ey’re p
                                 us      Th
                              hy
                             W

This way of doing things is much better than the AJAX way of doing things, by constantly
polling a source for new data every so often.

It saves bandwidth, which in turn saves everyone time and money.

It allows you to handle data immediately, literally the moment it has been created on the
other end of the connection.
ing
                                           g am rs
                                     W   eb een playe
                                   r
                                 ye ting b  etw
                            ipla       ica
                         ult      mm
                                     un
                        M       Co



WebSockets is perfect for multiplayer gaming.
Rawkets is a multiplayer space game that allows you to shoot your friends in the face with
HTML5 technologies.

Still not really at a beta release level yet, hence the bugs you might notice in this video.

http://rawkets.com
n  t
                                                 nte
                                               co        es
                                             g
                                          in tant u  pd
                                                       at

                                       am ins
                                   stre e and
                               ive       Liv
                              L

It’s also perfect for subscribing to a live feed of data.

News, stocks, Twitter, etc.
-07
                                                            ft
                                                          ra rtant
                                          &              Dpo
                                      -06            is im

                                  raft     ifferen
                                                  ce

                    6,           D        d
                                             the
                ft-7                   ow
                                         ing

             Dra                     Kn


Right now there are a growing number of specifications relating to WebSockets.

The current versions getting popular are Draft-06 and -07, which include changes to the old
Draft-76 that had potential security issues.

Most browsers up until now supported the older drafts, like -76, and the problem is that
Draft-06 and -07 aren’t compatible with -76.

This means that any browser that upgrades to the newer drafts won’t be able to communicate
with WebSockets connections that are running the older Draft-76. Nightmare!
o rt
                                                       p p
                                                   s u           al
                                              ser          no
                                                             tide

                                           row      nt,but
                                          B       ce
                                                         de
                                                   retty
                                                  P




I’m pleasantly surprised by the level of browser support for WebSockets.

Chrome, Safari, iOS, and Firefox (from the latest beta), support it out of the box.

It was disabled in a previous version of Firefox for security reasons, but the ability to enable
it through a preference was left in. The latest beta (version 6), is the first to fully support
WebSockets, although it has been prefixed until a later version. I’ll show you what I mean by
this in a moment.

Opera has disabled WebSockets for now, and both IE and Android do not support WebSockets
at all. IE is experimenting with WebSockets in an experimental release, but it’s not ready for
public use yet.

The browser situation is by no means ideal, but there’s certainly enough support to start
thinking about using the technology.
easy
                                                               is         PI
                                      kets                           rip
                                                                        tA
                                    oc                           vaSc
                                b S                        ple
                                                               Ja
                             e
                           W love                     a sim
                       ing       tta
                     Us     ou
                               go
                           Y


When I first started looking at WebSockets the first thing that I noticed was how easy it is to
use.

This sort of sums up how I feel about most of the new JavaScript APIs.
var ws = new WebSocket("ws://127.0.0.1:8080");




Connecting to a WebSocket server is as simple as calling a single constructor in JavaScript.

By calling WebSocket and passing in the address of the server, the connection will be
attempted automatically for you.

If the connection is successful then a WebSocket object will be returned for you to use later
on.
var ws = new MozWebSocket("ws://127.0.0.1:8080");




In the latest Firefox beta (version 6) you’ll need to use the prefixed constructor to connect to
a WebSocket server.

As of right now the latest Aurora build doesn’t require a prefix, but I cannot guarantee that
things will stay that way.
var ws = new WebSocket("ws://127.0.0.1:8080");


    ws.onopen = function() {
       console.log("Connected to WebSocket server");
    };


    ws.onclose = function() {
       console.log("Disconnected");
    };


    ws.onmessage = function(msg) {
       console.log("Message received: "+msg.data);
    };

The returned WebSockets object has some events that you can subscribe to.

onopen is fired when you have successfully connected to the WebSocket server.

onclose is fired when you have disconnected from the WebSocket server.

onmessage is fired when a new message is received from the WebSocket server.

You also have on onerror event to deal with issues with the WebSockets connection.
var ws = new WebSocket("ws://127.0.0.1:8080");


    ...


    ws.send(“Hello, world!”);




Use the send method to transmit a message to to WebSocket server.
var ws = new WebSocket("ws://127.0.0.1:8080");


     ...


     ws.close();




To close the WebSocket connection you just call the close method.

And that’s really about as complicated as it gets on the client side of things.
ve r
                                            ser
                                     t he        ne
                                                   ct to

                                  on         oc
                                               on
                            e ts         ingt

                        ock         om
                                      eth
                      bS        eeds
                    We     Yo
                             un



To get any proper mileage out of WebSockets you probably want to set up a server that can
send and receive data to clients connected through WebSockets.
My favourite way to do anything on the server right now is with Node.js.

I like Node because it’s powered by JavaScript and it’s supremely easy to use.

It isn’t the only option available though; most server-side platforms support the ability to
communicate through WebSockets.
npm install websocket




There are a variety of WebSockets modules around at the moment, but for full support of the
new drafts I’ve begun using the Node-Websocket module.

If you already have NPM installed then you can get the module with little effort.
var WebSocketServer = require("websocket").server;
    var http = require("http");


    var server = http.createServer(function(request, response) {});


    server.listen(8080, function() {
        console.log("Server is listening on port 8080");
    });


    var ws = new WebSocketServer({
        httpServer: server,
        autoAcceptConnections: true
    });




This is how we can set up a simple WebSockets echo system. Anything that is sent to the
server will be sent back again. It’s useful for testing.
...


ws.on("connect", function(conn) {
    console.log("Connection accepted");
    conn.on("message", function(message) {
        if (message.type === "utf8") {
            console.log("Received Message: "+message.utf8Data);
            conn.sendUTF(message.utf8Data);
        };
    });
    conn.on("close", function(conn) {
        console.log("Client "+conn.remoteAddress+" disconnected");
    });
});
Socket.IO is a Node module that provides powerful real-time communication through
WebSockets.

Don’t be fooled by how much you can do with it though, it’s surprisingly simple to use.
sers
                                                          row      ne
                                     ld       ev
                                                         b     eryo
                                  r o     ort
                               fo can supp
                            ack you
                        allb     ow
                       F        N



The great thing about Socket.IO is that it falls back to Flash for socket communication in
browsers that don’t support WebSockets.

You can also let Socket.IO fallback from WebSockets to other methods of communication, like
long-polling, etc.
var io = require("socket.io").listen(8080);


     io.sockets.on("connection", function (socket) {
        socket.on("message", function (data) {
           socket.emit(data);
        });
     });




This is a simple Socket.IO version of the echo server.

I’d show you it working, but I kind of broke it on the train over here and I didn’t get a chance
to fix it up.

The cool thing about Socket.IO is that you can set it up in one line, rather than 4 in the other
method.
m e
                                                    eso ics
                                                  aw e bas
                                                st ond th
                                              ju bey
                                           is
                          t.IO                         goes

                      ocke                          It

                     S

Socket.IO does much more than just simple WebSockets communication.

Automatically packages up messages and deals with JSON messages.

Volatile messages that can be dropped if the client is busy.

The ability to split a single connection into channels so you can have different things
happening across the same stream.

This is great for concepts like chat rooms, or splitting functionality in multiplayer games.
as
                                                o tch e
                                              g
                                         ets e first   tim

                                    ock           th
                                  bS         e up
                                 e
                                W e trippe
                                           dm

                                         es
                                       Th


There are a few key issues that may trip you up with WebSockets.

The main one is to be aware that you’re using TCP, which means that you may get times
where sent packets are having to be resent so the stream can catch up.

This is most noticeable with multiplayer gaming as the amount of data being sent is pretty
intensive.
ce  s
                                                  ervi
                                              al s       ro
                                                            wn
                                            rn o roll y
                                          te ve t
                                                       ou

                                        ex
                             ing                  ys
                                                     ha
                           Us                 alw
                                                 a
                                 on’t
                                     ud
                                   Yo

There are a whole host of solutions available if you just want to use WebSockets and not have
to worry about all the underlying functionality.

Here are a few of my favourites.
Pusher is for real-time communication and uses WebSockets.

Remotely hosted.

Quite a lot of services are starting to use Pusher now.

I believe some of the Pusher guys are in the room tonight as well.
Joyent’s Node cloud servers

Provides a remotely hosted Node server that allows you to quickly get a WebSocket server up
and running.
d  s
                                           ee
                                       s n
                                    et          t-ish
                                ock e is bri  gh
                              bS        ur
                            We      ef
                                      ut
                          t       Th
                        ha
                       W

Non-text-based communication, which will help for compression and other cool stuff.

UDP support, which is possible but doubtful for now. I know that people are looking into this
for media streaming, so perhaps it will move across.
ROB HAWKES
            @robhawkes




            Rawkes.com
            Personal website and blog

   RECENT PROJECTS                       MORE COOL STUFF


            Twitter sentiment analysis          Mozilla Technical Evangelist
            Delving into your soul.             My job


            Rawkets.com                         ExplicitWeb.co.uk
            HTML5 & WebSockets game.            Web development podcast.


Twitter - @robhawkes
Rawkes - http://rawkes.com
DEV DERBY
    Experimenting with the latest Web technologies




                                                     Every month

                                                     This month is HTML5 video

                                                     Manipulate video with canvas

                                                     Win prizes (like an Android)

                                                     Next month is all about touch

                     DEVELOPER.MOZILLA.ORG/EN-US/DEMOS/DEVDERBY




Also, you should definitely take part in the Dev Derby, which is a monthly competition run by
the Mozilla Developer Network to see what can be done with the latest Web technologies.

This month the focus is on HTML5 video, which is pretty interesting considering that you can
manipulate it using the canvas.

The winners get cool prizes, like an Android phone. It’s a great excuse to play around with
these technologies.

https://developer.mozilla.org/en-US/demos/devderby
O U
                             Y s?
                           K tion
                          N ues
                         A yq
                       TH An                                    R b
                                                                       es
                                                                     wk es
                                                                   Ha wk
                                                                 ob ha
                                                                  ro
                                                                 @




Thank you.

If you have any questions feel free to grab me on Twitter (@robhawkes), or email
rob@rawkes.com

WebSockets - Embracing the real-time Web

  • 1.
    T S KE C eb O W S me B -ti E al W he re Ro bH aw kes g t cin bra Em Hi, I’m Rob Hawkes and I’m here tonight to talk a little about WebSockets and why they’re amazing.
  • 2.
    If you don’talready know, I work at Mozilla. My official job title is Technical Evangelist, but I prefer Rawket Scientist, which is what it says on my business card. Part of my job is to engage with developers like you and me about cool new technologies on the Web.
  • 3.
    Created by PhilBanks (@emirpprime) Aside from that I spend most of my time experimenting with HTML5 and other cool technologies. If you’ve met me before then you probably already know about my slight addiction to canvas and visual programming. It’s fun!
  • 4.
    Unfortunately I’m stillin jet-lag mode at the moment. I flew back on Saturday after spending a week in the US with Mozilla and talking about HTML5 gaming. On Saturday night I slept a total of 2 hours, and last night I managed to squeeze in a good 7. So I apologise in advance if we find that having 9 hours of sleep in the past 60 turns me in a gibbering wreck.
  • 5.
    ts ? e ck ugs So e b ith pl W to do w are hing at ot Wh N Who already knows what WebSockets are? Bi-directional communication, created by upgrading a standard HTTP connection. Allows for data to be sent back and forth at the same time and without having to request it. To clarify; once a WebSockets connection is made, data is pushed across it without either side having to ask for it.
  • 6.
    ts ? e ck ool S o eb retty c e W ey’re p us Th hy W This way of doing things is much better than the AJAX way of doing things, by constantly polling a source for new data every so often. It saves bandwidth, which in turn saves everyone time and money. It allows you to handle data immediately, literally the moment it has been created on the other end of the connection.
  • 7.
    ing g am rs W eb een playe r ye ting b etw ipla ica ult mm un M Co WebSockets is perfect for multiplayer gaming.
  • 8.
    Rawkets is amultiplayer space game that allows you to shoot your friends in the face with HTML5 technologies. Still not really at a beta release level yet, hence the bugs you might notice in this video. http://rawkets.com
  • 9.
    n t nte co es g in tant u pd at am ins stre e and ive Liv L It’s also perfect for subscribing to a live feed of data. News, stocks, Twitter, etc.
  • 10.
    -07 ft ra rtant & Dpo -06 is im raft ifferen ce 6, D d the ft-7 ow ing Dra Kn Right now there are a growing number of specifications relating to WebSockets. The current versions getting popular are Draft-06 and -07, which include changes to the old Draft-76 that had potential security issues. Most browsers up until now supported the older drafts, like -76, and the problem is that Draft-06 and -07 aren’t compatible with -76. This means that any browser that upgrades to the newer drafts won’t be able to communicate with WebSockets connections that are running the older Draft-76. Nightmare!
  • 11.
    o rt p p s u al ser no tide row nt,but B ce de retty P I’m pleasantly surprised by the level of browser support for WebSockets. Chrome, Safari, iOS, and Firefox (from the latest beta), support it out of the box. It was disabled in a previous version of Firefox for security reasons, but the ability to enable it through a preference was left in. The latest beta (version 6), is the first to fully support WebSockets, although it has been prefixed until a later version. I’ll show you what I mean by this in a moment. Opera has disabled WebSockets for now, and both IE and Android do not support WebSockets at all. IE is experimenting with WebSockets in an experimental release, but it’s not ready for public use yet. The browser situation is by no means ideal, but there’s certainly enough support to start thinking about using the technology.
  • 12.
    easy is PI kets rip tA oc vaSc b S ple Ja e W love a sim ing tta Us ou go Y When I first started looking at WebSockets the first thing that I noticed was how easy it is to use. This sort of sums up how I feel about most of the new JavaScript APIs.
  • 13.
    var ws =new WebSocket("ws://127.0.0.1:8080"); Connecting to a WebSocket server is as simple as calling a single constructor in JavaScript. By calling WebSocket and passing in the address of the server, the connection will be attempted automatically for you. If the connection is successful then a WebSocket object will be returned for you to use later on.
  • 14.
    var ws =new MozWebSocket("ws://127.0.0.1:8080"); In the latest Firefox beta (version 6) you’ll need to use the prefixed constructor to connect to a WebSocket server. As of right now the latest Aurora build doesn’t require a prefix, but I cannot guarantee that things will stay that way.
  • 15.
    var ws =new WebSocket("ws://127.0.0.1:8080"); ws.onopen = function() { console.log("Connected to WebSocket server"); }; ws.onclose = function() { console.log("Disconnected"); }; ws.onmessage = function(msg) { console.log("Message received: "+msg.data); }; The returned WebSockets object has some events that you can subscribe to. onopen is fired when you have successfully connected to the WebSocket server. onclose is fired when you have disconnected from the WebSocket server. onmessage is fired when a new message is received from the WebSocket server. You also have on onerror event to deal with issues with the WebSockets connection.
  • 16.
    var ws =new WebSocket("ws://127.0.0.1:8080"); ... ws.send(“Hello, world!”); Use the send method to transmit a message to to WebSocket server.
  • 17.
    var ws =new WebSocket("ws://127.0.0.1:8080"); ... ws.close(); To close the WebSocket connection you just call the close method. And that’s really about as complicated as it gets on the client side of things.
  • 18.
    ve r ser t he ne ct to on oc on e ts ingt ock om eth bS eeds We Yo un To get any proper mileage out of WebSockets you probably want to set up a server that can send and receive data to clients connected through WebSockets.
  • 19.
    My favourite wayto do anything on the server right now is with Node.js. I like Node because it’s powered by JavaScript and it’s supremely easy to use. It isn’t the only option available though; most server-side platforms support the ability to communicate through WebSockets.
  • 20.
    npm install websocket Thereare a variety of WebSockets modules around at the moment, but for full support of the new drafts I’ve begun using the Node-Websocket module. If you already have NPM installed then you can get the module with little effort.
  • 21.
    var WebSocketServer =require("websocket").server; var http = require("http"); var server = http.createServer(function(request, response) {}); server.listen(8080, function() { console.log("Server is listening on port 8080"); }); var ws = new WebSocketServer({ httpServer: server, autoAcceptConnections: true }); This is how we can set up a simple WebSockets echo system. Anything that is sent to the server will be sent back again. It’s useful for testing.
  • 22.
    ... ws.on("connect", function(conn) { console.log("Connection accepted"); conn.on("message", function(message) { if (message.type === "utf8") { console.log("Received Message: "+message.utf8Data); conn.sendUTF(message.utf8Data); }; }); conn.on("close", function(conn) { console.log("Client "+conn.remoteAddress+" disconnected"); }); });
  • 23.
    Socket.IO is aNode module that provides powerful real-time communication through WebSockets. Don’t be fooled by how much you can do with it though, it’s surprisingly simple to use.
  • 24.
    sers row ne ld ev b eryo r o ort fo can supp ack you allb ow F N The great thing about Socket.IO is that it falls back to Flash for socket communication in browsers that don’t support WebSockets. You can also let Socket.IO fallback from WebSockets to other methods of communication, like long-polling, etc.
  • 25.
    var io =require("socket.io").listen(8080); io.sockets.on("connection", function (socket) { socket.on("message", function (data) { socket.emit(data); }); }); This is a simple Socket.IO version of the echo server. I’d show you it working, but I kind of broke it on the train over here and I didn’t get a chance to fix it up. The cool thing about Socket.IO is that you can set it up in one line, rather than 4 in the other method.
  • 26.
    m e eso ics aw e bas st ond th ju bey is t.IO goes ocke It S Socket.IO does much more than just simple WebSockets communication. Automatically packages up messages and deals with JSON messages. Volatile messages that can be dropped if the client is busy. The ability to split a single connection into channels so you can have different things happening across the same stream. This is great for concepts like chat rooms, or splitting functionality in multiplayer games.
  • 27.
    as o tch e g ets e first tim ock th bS e up e W e trippe dm es Th There are a few key issues that may trip you up with WebSockets. The main one is to be aware that you’re using TCP, which means that you may get times where sent packets are having to be resent so the stream can catch up. This is most noticeable with multiplayer gaming as the amount of data being sent is pretty intensive.
  • 28.
    ce s ervi al s ro wn rn o roll y te ve t ou ex ing ys ha Us alw a on’t ud Yo There are a whole host of solutions available if you just want to use WebSockets and not have to worry about all the underlying functionality. Here are a few of my favourites.
  • 29.
    Pusher is forreal-time communication and uses WebSockets. Remotely hosted. Quite a lot of services are starting to use Pusher now. I believe some of the Pusher guys are in the room tonight as well.
  • 30.
    Joyent’s Node cloudservers Provides a remotely hosted Node server that allows you to quickly get a WebSocket server up and running.
  • 31.
    d s ee s n et t-ish ock e is bri gh bS ur We ef ut t Th ha W Non-text-based communication, which will help for compression and other cool stuff. UDP support, which is possible but doubtful for now. I know that people are looking into this for media streaming, so perhaps it will move across.
  • 32.
    ROB HAWKES @robhawkes Rawkes.com Personal website and blog RECENT PROJECTS MORE COOL STUFF Twitter sentiment analysis Mozilla Technical Evangelist Delving into your soul. My job Rawkets.com ExplicitWeb.co.uk HTML5 & WebSockets game. Web development podcast. Twitter - @robhawkes Rawkes - http://rawkes.com
  • 33.
    DEV DERBY Experimenting with the latest Web technologies Every month This month is HTML5 video Manipulate video with canvas Win prizes (like an Android) Next month is all about touch DEVELOPER.MOZILLA.ORG/EN-US/DEMOS/DEVDERBY Also, you should definitely take part in the Dev Derby, which is a monthly competition run by the Mozilla Developer Network to see what can be done with the latest Web technologies. This month the focus is on HTML5 video, which is pretty interesting considering that you can manipulate it using the canvas. The winners get cool prizes, like an Android phone. It’s a great excuse to play around with these technologies. https://developer.mozilla.org/en-US/demos/devderby
  • 34.
    O U Y s? K tion N ues A yq TH An R b es wk es Ha wk ob ha ro @ Thank you. If you have any questions feel free to grab me on Twitter (@robhawkes), or email rob@rawkes.com