Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

WebSockets - Embracing the real-time Web


Published on

Published in: Technology
  • Be the first to comment

WebSockets - Embracing the real-time Web

  1. 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 EmHi, I’m Rob Hawkes and I’m here tonight to talk a little about WebSockets and why they’reamazing.
  2. 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 sayson my business card.Part of my job is to engage with developers like you and me about cool new technologies onthe Web.
  3. 3. Created by Phil Banks (@emirpprime)Aside from that I spend most of my time experimenting with HTML5 and other cooltechnologies.If you’ve met me before then you probably already know about my slight addiction to canvasand visual programming.It’s fun!
  4. 4. Unfortunately I’m still in jet-lag mode at the moment. I flew back on Saturday after spendinga 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 agibbering wreck.
  5. 5. ts ? e ck ugs So e b ith pl W to do w are hing at ot Wh NWho 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 sidehaving to ask for it.
  6. 6. ts ? e ck ool S o eb retty c e W ey’re p us Th hy WThis way of doing things is much better than the AJAX way of doing things, by constantlypolling 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 theother end of the connection.
  7. 7. ing g am rs W eb een playe r ye ting b etw ipla ica ult mm un M CoWebSockets is perfect for multiplayer gaming.
  8. 8. Rawkets is a multiplayer space game that allows you to shoot your friends in the face withHTML5 technologies.Still not really at a beta release level yet, hence the bugs you might notice in this video.
  9. 9. n t nte co es g in tant u pd at am ins stre e and ive Liv LIt’s also perfect for subscribing to a live feed of data.News, stocks, Twitter, etc.
  10. 10. -07 ft ra rtant & Dpo -06 is im raft ifferen ce 6, D d the ft-7 ow ing Dra KnRight 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 oldDraft-76 that had potential security issues.Most browsers up until now supported the older drafts, like -76, and the problem is thatDraft-06 and -07 aren’t compatible with -76.This means that any browser that upgrades to the newer drafts won’t be able to communicatewith WebSockets connections that are running the older Draft-76. Nightmare!
  11. 11. o rt p p s u al ser no tide row nt,but B ce de retty PI’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 enableit through a preference was left in. The latest beta (version 6), is the first to fully supportWebSockets, although it has been prefixed until a later version. I’ll show you what I mean bythis in a moment.Opera has disabled WebSockets for now, and both IE and Android do not support WebSocketsat all. IE is experimenting with WebSockets in an experimental release, but it’s not ready forpublic use yet.The browser situation is by no means ideal, but there’s certainly enough support to startthinking about using the technology.
  12. 12. easy is PI kets rip tA oc vaSc b S ple Ja e W love a sim ing tta Us ou go YWhen I first started looking at WebSockets the first thing that I noticed was how easy it is touse.This sort of sums up how I feel about most of the new JavaScript APIs.
  13. 13. var ws = new WebSocket("ws://");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 beattempted automatically for you.If the connection is successful then a WebSocket object will be returned for you to use lateron.
  14. 14. var ws = new MozWebSocket("ws://");In the latest Firefox beta (version 6) you’ll need to use the prefixed constructor to connect toa WebSocket server.As of right now the latest Aurora build doesn’t require a prefix, but I cannot guarantee thatthings will stay that way.
  15. 15. var ws = new WebSocket("ws://"); ws.onopen = function() { console.log("Connected to WebSocket server"); }; ws.onclose = function() { console.log("Disconnected"); }; ws.onmessage = function(msg) { console.log("Message received: "; };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. 16. var ws = new WebSocket("ws://"); ... ws.send(“Hello, world!”);Use the send method to transmit a message to to WebSocket server.
  17. 17. var ws = new WebSocket("ws://"); ... 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. 18. ve r ser t he ne ct to on oc on e ts ingt ock om eth bS eeds We Yo unTo get any proper mileage out of WebSockets you probably want to set up a server that cansend and receive data to clients connected through WebSockets.
  19. 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 tocommunicate through WebSockets.
  20. 20. npm install websocketThere are a variety of WebSockets modules around at the moment, but for full support of thenew 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. 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 theserver will be sent back again. It’s useful for testing.
  22. 22."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. 23. Socket.IO is a Node module that provides powerful real-time communication throughWebSockets.Don’t be fooled by how much you can do with it though, it’s surprisingly simple to use.
  24. 24. sers row ne ld ev b eryo r o ort fo can supp ack you allb ow F NThe great thing about Socket.IO is that it falls back to Flash for socket communication inbrowsers that don’t support WebSockets.You can also let Socket.IO fallback from WebSockets to other methods of communication, likelong-polling, etc.
  25. 25. var io = require("").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 chanceto fix it up.The cool thing about Socket.IO is that you can set it up in one line, rather than 4 in the othermethod.
  26. 26. m e eso ics aw e bas st ond th ju bey is t.IO goes ocke It SSocket.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 thingshappening across the same stream.This is great for concepts like chat rooms, or splitting functionality in multiplayer games.
  27. 27. as o tch e g ets e first tim ock th bS e up e W e trippe dm es ThThere 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 timeswhere 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 prettyintensive.
  28. 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 YoThere are a whole host of solutions available if you just want to use WebSockets and not haveto worry about all the underlying functionality.Here are a few of my favourites.
  29. 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. 30. Joyent’s Node cloud serversProvides a remotely hosted Node server that allows you to quickly get a WebSocket server upand running.
  31. 31. d s ee s n et t-ish ock e is bri gh bS ur We ef ut t Th ha WNon-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 thisfor media streaming, so perhaps it will move across.
  32. 32. ROB HAWKES @robhawkes Personal website and blog RECENT PROJECTS MORE COOL STUFF Twitter sentiment analysis Mozilla Technical Evangelist Delving into your soul. My job HTML5 & WebSockets game. Web development podcast.Twitter - @robhawkesRawkes -
  33. 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/DEVDERBYAlso, you should definitely take part in the Dev Derby, which is a monthly competition run bythe 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 canmanipulate it using the canvas.The winners get cool prizes, like an Android phone. It’s a great excuse to play around withthese technologies.
  34. 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