34
WEBSOCKETS Embracing the real-time Web Rob Hawkes Hi, I’m Rob Hawkes and I’m here tonight to talk a little about WebSockets and why they’re amazing.

WebSockets - Embracing the real-time Web

Embed Size (px)

Citation preview

Page 1: WebSockets - Embracing the real-time Web

WEBSOCKETS

Embracing the real-time Web

Rob Hawkes

Hi, I’m Rob Hawkes and I’m here tonight to talk a little about WebSockets and why they’re amazing.

Page 2: WebSockets - Embracing the real-time Web

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.

Page 3: WebSockets - Embracing the real-time 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!

Page 4: WebSockets - Embracing the real-time Web

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.

Page 5: WebSockets - Embracing the real-time Web

What are WebSockets?

Nothing to do with plugs

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.

Page 6: WebSockets - Embracing the real-time Web

Why use WebSockets?

They’re pretty cool

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.

Page 7: WebSockets - Embracing the real-time Web

Multiplayer W

eb gaming

Communicating between players

WebSockets is perfect for multiplayer gaming.

Page 8: WebSockets - Embracing the real-time Web

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

Page 9: WebSockets - Embracing the real-time Web

Live streaming content

Live and instant updates

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

News, stocks, Twitter, etc.

Page 10: WebSockets - Embracing the real-time Web

Draft-76, Draft-06 & Draft-07

Knowing the difference is im

portant

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!

Page 11: WebSockets - Embracing the real-time Web

Browser support

Pretty decent, but not ideal

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.

Page 12: WebSockets - Embracing the real-time Web

Using WebSockets is easy

You gotta love a simple JavaScript API

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.

Page 13: WebSockets - Embracing the real-time Web

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.

Page 14: WebSockets - Embracing the real-time Web

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.

Page 15: WebSockets - Embracing the real-time Web

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.

Page 16: WebSockets - Embracing the real-time Web

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.

Page 17: WebSockets - Embracing the real-time Web

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.

Page 18: WebSockets - Embracing the real-time Web

WebSockets on the server

You need something to connect to

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.

Page 19: WebSockets - Embracing the real-time Web

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.

Page 20: WebSockets - Embracing the real-time Web

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.

Page 21: WebSockets - Embracing the real-time Web

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.

Page 22: WebSockets - Embracing the real-time Web

...

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");

});

});

Page 23: WebSockets - Embracing the real-time Web

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.

Page 24: WebSockets - Embracing the real-time Web

Fallback for old browsers

Now you can support everyone

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.

Page 25: WebSockets - Embracing the real-time Web

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.

Page 26: WebSockets - Embracing the real-time Web

Socket.IO is just awesome

It goes beyond the basics

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.

Page 27: WebSockets - Embracing the real-time Web

WebSockets gotchas

These tripped me up the firs

t time

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.

Page 28: WebSockets - Embracing the real-time Web

Using external services

You don’t always have to roll your own

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.

Page 29: WebSockets - Embracing the real-time Web

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.

Page 30: WebSockets - Embracing the real-time Web

Joyent’s Node cloud servers

Provides a remotely hosted Node server that allows you to quickly get a WebSocket server up and running.

Page 31: WebSockets - Embracing the real-time Web

What WebSockets needs

The future is bright-ish

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.

Page 32: WebSockets - Embracing the real-time Web

Rawkets.comHTML5 & WebSockets game.

Twitter sentiment analysisDelving into your soul.

RECENT PROJECTS

Rawkes.comPersonal website and blog

MORE COOL STUFF

ExplicitWeb.co.ukWeb development podcast.

Mozilla Technical EvangelistMy job

ROB HAWKES@robhawkes

Twitter - @robhawkesRawkes - http://rawkes.com

Page 33: WebSockets - Embracing the real-time Web

DEV DERBYExperimenting with the latest Web technologies

Manipulate video with canvas

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

Every month

This month is HTML5 video

Win prizes (like an Android)

Next month is all about touch

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

Page 34: WebSockets - Embracing the real-time Web

THANK YOU

Any questions?

Rob Hawkes

@robhawkes

Thank you.

If you have any questions feel free to grab me on Twitter (@robhawkes), or email [email protected]