SlideShare a Scribd company logo
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

More Related Content

PDF
Learning sessions #5 pre incubator - BooTown
PDF
Profil Ringkas INSPIRASI BAKAT
PPSX
大山里的人(二)
PPT
Redefine Representation
PPTX
Nrrc promising resilience perspectives 7 2013 f
PDF
Analytics GAE - Plurk Avatar History 20090825-20090909
PDF
Usp dh 2013
PDF
2013 01 24 learning sessions 4 presentation hope stone
Learning sessions #5 pre incubator - BooTown
Profil Ringkas INSPIRASI BAKAT
大山里的人(二)
Redefine Representation
Nrrc promising resilience perspectives 7 2013 f
Analytics GAE - Plurk Avatar History 20090825-20090909
Usp dh 2013
2013 01 24 learning sessions 4 presentation hope stone

Viewers also liked (19)

PDF
Majalah INFO-UFO no 01
DOC
Sexologia: Repaso para el final
PPT
PPT
υπολογιστέςκαι ιστορία
PDF
Inside Rawkets - onGameStart
PPT
E write writing for the web 1-2 june2011
PDF
020615 Jewish Networking Congress
PPT
E write - loc advanced writing for the web 23 may2011
PPT
Cahokia:Collapsing Inot Thin Air
PDF
HTML5 Technologies for Game Development - Web Directions Code
KEY
Rawkets - A Massively Multiplayer HTML5 Game [Mozilla GameOn10]
PPT
Session4 pl online_course_30_september2011
PPS
780 吴冠中画 3(Hys 2009)
PPS
Wilfreda - Oscar
DOCX
Keaksaraan sebagai fondasi pendidikan nasional
PDF
影像紀錄區開發歷程
PDF
040709 Iajgs Powerful Technologies Genealogy
PDF
FY12 Pre-Incubator Workshop
DOCX
Ettore
Majalah INFO-UFO no 01
Sexologia: Repaso para el final
υπολογιστέςκαι ιστορία
Inside Rawkets - onGameStart
E write writing for the web 1-2 june2011
020615 Jewish Networking Congress
E write - loc advanced writing for the web 23 may2011
Cahokia:Collapsing Inot Thin Air
HTML5 Technologies for Game Development - Web Directions Code
Rawkets - A Massively Multiplayer HTML5 Game [Mozilla GameOn10]
Session4 pl online_course_30_september2011
780 吴冠中画 3(Hys 2009)
Wilfreda - Oscar
Keaksaraan sebagai fondasi pendidikan nasional
影像紀錄區開發歷程
040709 Iajgs Powerful Technologies Genealogy
FY12 Pre-Incubator Workshop
Ettore
Ad

Similar to WebSockets - Embracing the real-time Web (20)

PDF
Geek Meet - Boot to Gecko: The Future of Mobile?
PDF
MDN Hackday London - Boot to Gecko: The Future of Mobile
PDF
Melbourne Geek Night - Boot to Gecko – The Web as a Platform
PDF
Boot to Gecko – The Web as a Platform
PDF
Awesome Technology on the Web - Oxygen Accelerator
PDF
MelbJS - Inside Rawkets
PDF
Open Web Apps and the Mozilla Labs Apps project
PDF
Tomorrow's Web and Future Technologies - WDC2011
PDF
HTML5 & JavaScript: The Future Now
PDF
NY HTML5 - Game Development with HTML5 & JavaScript
PDF
Hacking with B2G – Web Apps and Customisation
PDF
Firefox OS / B2G and the future of the web
PDF
Open Web Games using HTML5 & JavaScript
PDF
Browserscene: Creating demos on the Web
PDF
Open Web Games with HTML5 & JavaScript
PDF
Session 18 Per Olof Arnäs
PDF
SocialMedia Technologies
PDF
Mozilla Firefox: Present and Future - Fluent JS
PDF
Making social media work for you | StreetGames National Conference 2013
PDF
20 thingsi learnedaboutbrowsersandtheweb
Geek Meet - Boot to Gecko: The Future of Mobile?
MDN Hackday London - Boot to Gecko: The Future of Mobile
Melbourne Geek Night - Boot to Gecko – The Web as a Platform
Boot to Gecko – The Web as a Platform
Awesome Technology on the Web - Oxygen Accelerator
MelbJS - Inside Rawkets
Open Web Apps and the Mozilla Labs Apps project
Tomorrow's Web and Future Technologies - WDC2011
HTML5 & JavaScript: The Future Now
NY HTML5 - Game Development with HTML5 & JavaScript
Hacking with B2G – Web Apps and Customisation
Firefox OS / B2G and the future of the web
Open Web Games using HTML5 & JavaScript
Browserscene: Creating demos on the Web
Open Web Games with HTML5 & JavaScript
Session 18 Per Olof Arnäs
SocialMedia Technologies
Mozilla Firefox: Present and Future - Fluent JS
Making social media work for you | StreetGames National Conference 2013
20 thingsi learnedaboutbrowsersandtheweb
Ad

More from Robin Hawkes (15)

PDF
ViziCities - Lessons Learnt Visualising Real-world Cities in 3D
PDF
Understanding cities using ViziCities and 3D data visualisation
PDF
Calculating building heights using a phone camera
PDF
WebVisions – ViziCities: Bringing Cities to Life Using Big Data
PDF
Understanding cities using ViziCities and 3D data visualisation
PDF
ViziCities: Creating Real-World Cities in 3D using OpenStreetMap and WebGL
PDF
Beautiful Data Visualisation & D3
PDF
ViziCities: Making SimCity for the Real World
PDF
The State of WebRTC
PDF
Bringing Cities to Life Using Big Data & WebGL
PDF
Mobile App Development - Pitfalls & Helpers
PDF
The State of HTML5 Games - Fluent JS
PDF
MDN Hackday London - Open Web Games with HTML5 & JavaScript
PDF
HTML5 Games - Not Just for Gamers
PDF
Open Web Games with HTML5 & JavaScript
ViziCities - Lessons Learnt Visualising Real-world Cities in 3D
Understanding cities using ViziCities and 3D data visualisation
Calculating building heights using a phone camera
WebVisions – ViziCities: Bringing Cities to Life Using Big Data
Understanding cities using ViziCities and 3D data visualisation
ViziCities: Creating Real-World Cities in 3D using OpenStreetMap and WebGL
Beautiful Data Visualisation & D3
ViziCities: Making SimCity for the Real World
The State of WebRTC
Bringing Cities to Life Using Big Data & WebGL
Mobile App Development - Pitfalls & Helpers
The State of HTML5 Games - Fluent JS
MDN Hackday London - Open Web Games with HTML5 & JavaScript
HTML5 Games - Not Just for Gamers
Open Web Games with HTML5 & JavaScript

Recently uploaded (20)

PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
project resource management chapter-09.pdf
PPTX
Chapter 5: Probability Theory and Statistics
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Developing a website for English-speaking practice to English as a foreign la...
PPTX
The various Industrial Revolutions .pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPT
What is a Computer? Input Devices /output devices
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Group 1 Presentation -Planning and Decision Making .pptx
project resource management chapter-09.pdf
Chapter 5: Probability Theory and Statistics
1 - Historical Antecedents, Social Consideration.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
A contest of sentiment analysis: k-nearest neighbor versus neural network
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
NewMind AI Weekly Chronicles - August'25-Week II
Enhancing emotion recognition model for a student engagement use case through...
Developing a website for English-speaking practice to English as a foreign la...
The various Industrial Revolutions .pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
O2C Customer Invoices to Receipt V15A.pptx
What is a Computer? Input Devices /output devices
Univ-Connecticut-ChatGPT-Presentaion.pdf
observCloud-Native Containerability and monitoring.pptx
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx

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’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.
  • 3. 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!
  • 4. 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.
  • 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 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
  • 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 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.
  • 20. 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.
  • 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 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.
  • 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 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.
  • 30. Joyent’s Node cloud servers 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