Slide 1

Slide 1 text

WebSockets& Server-Sent Events by Kim Joar Bekkelund

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

kim joar bekkelund kimjoar.net

Slide 6

Slide 6 text

the legacy web real-time &

Slide 7

Slide 7 text

Polling Client Server

Slide 8

Slide 8 text

Polling HTTP overhead per message – Polling logic in the client – 1 GET = 1 HTTP request and maybe data

Slide 9

Slide 9 text

Long-polling Client Server 30s

Slide 10

Slide 10 text

Long-polling Client Server 30s (function poll(){ $.ajax({ url: "/some-url", dataType: "json", timeout: 30000, success: function(data) { // handle data }, complete: poll }); })();

Slide 11

Slide 11 text

Long-polling Client Server 30s (function poll(){ $.ajax({ url: "/some-url", dataType: "json", timeout: 30000, success: function(data) { // handle data }, complete: poll }); })();

Slide 12

Slide 12 text

Long-polling Less HTTP overhead + Polling logic in the client – 1 GET = 1 HTTP request and often data

Slide 13

Slide 13 text

Streaming Client Server Transfer-Encoding: chunked append <script>

Slide 14

Slide 14 text

Streaming “forever frame” Less HTTP overhead + Error handling – What’s going on? –

Slide 15

Slide 15 text

oh, come on …

Slide 16

Slide 16 text

WebSockets

Slide 17

Slide 17 text

WebSockets Client Server Set up connection

Slide 18

Slide 18 text

WebSockets Bidirectional Server and client can send and receive Full-duplex Server and client can send at the same time Not HTTP Minimal overhead per message Across domains No same-origin policy No constraint on payload Handles both text and binary data

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

Simplest setup for getting started with WebSockets

Slide 24

Slide 24 text

var ws = new WebSocket('ws://localhost:8123'); ws.onopen = function() { ws.send('yay! we connected!'); }; ws.onmessage = function(event) { console.log('Received from server: ' + event.data); }; HTML

Slide 25

Slide 25 text

HTML $ python -m SimpleHTTPServer

Slide 26

Slide 26 text

var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8123 }); wss.on('connection', function(ws) { ws.send('Server says hello'); ws.on('message', function(message) { console.log('Received from client:', message); }); }); app.js

Slide 27

Slide 27 text

var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8123 }); wss.on('connection', function(ws) { ws.send('Server says hello'); ws.on('message', function(message) { console.log('Received from client:', message); }); }); app.js node app.js

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

that’s it

Slide 33

Slide 33 text

vs (W3C) WebSocket API WebSocket Protocol (IETF)

Slide 34

Slide 34 text

WebSocket Protocol (IETF) RFC6455 “Minimalistic” protocol above TCP Starts out as HTTP Designed to work on port 80 and 443 Defines new URL schema: ws and wss

Slide 35

Slide 35 text

WebSocket Protocol (IETF) Request GET / HTTP/1.1 Host: localhost:8123 Origin: http://localhost:8000 Connection: Upgrade Upgrade: websocket Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 Response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Slide 36

Slide 36 text

WebSocket Protocol (IETF) Request Response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= GET / HTTP/1.1 Host: localhost:8123 Origin: http://localhost:8000 Connection: Upgrade Upgrade: websocket Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13

Slide 37

Slide 37 text

HTTP WebSocket upgrade

Slide 38

Slide 38 text

http://chimera.labs.oreilly.com/books/1230000000545/ch17.html WebSocket Protocol (IETF) 2–10 byte overhead for server-sent message 6–14 byte overhead for client-sent message

Slide 39

Slide 39 text

pros cons & Minimal overhead has

Slide 40

Slide 40 text

pros cons & Minimal overhead has gzip? cookies? response code? caching?

Slide 41

Slide 41 text

No metadata on every message

Slide 42

Slide 42 text

subprotocol agree on message format No metadata on every message

Slide 43

Slide 43 text

var ws = new WebSocket('wss://example.org/socket', ['minProtocol', 'minProtocol-v2']); ws.onopen = function() { if (ws.protocol == 'minProtocol-v2') { // ... } else { // ... } }

Slide 44

Slide 44 text

Use as a transport layer for standard application-level protocols?

Slide 45

Slide 45 text

+

Slide 46

Slide 46 text

Has no effect on the core WebSocket API

Slide 47

Slide 47 text

PROXY & FIREWALL

Slide 48

Slide 48 text

PROXY & FIREWALL WSS use

Slide 49

Slide 49 text

PROXY & FIREWALL WSS use ♥ HEARTBEAT

Slide 50

Slide 50 text

“The protocol is designed to allow for extensions, which will add capabilities to the base protocol.”

Slide 51

Slide 51 text

Client Server large message No multiplexing

Slide 52

Slide 52 text

No multiplexing Client Server Head-of-Line Blocking – all others are blocked large message

Slide 53

Slide 53 text

No multiplexing Client Server Head-of-Line Blocking – all others are blocked “A Multiplexing Extension for WebSockets” large message

Slide 54

Slide 54 text

No multiplexing Client Server

Slide 55

Slide 55 text

(W3C) WebSocket API

Slide 56

Slide 56 text

(W3C) WebSocket API W3C Candidate Recommendation "significant features are mostly locked"

Slide 57

Slide 57 text

var ws = new WebSocket(url[, protocols]); ws.onopen = function(e) { }; ws.onmessage = function(e) { console.log(e.data) }; ws.onerror = function(e) { console.log(e.code, e.reason) }; ws.onclose = function(e) { }; ws.send(message); (W3C) WebSocket API

Slide 58

Slide 58 text

var ws = new WebSocket(url[, protocols]); ws.onmessage = function(msg) { if (msg.data instanceof Blob) { processBlob(msg.data); } else { processText(msg.data); } }; (W3C) WebSocket API

Slide 59

Slide 59 text

ws.send(message); ws.send(message); ws.send(message); ws.send(message); … ws.send(message); ws.send(message); ws.send(message); ws.send(message); if (ws.bufferedAmount < threshold) { ws.send(message); } THROTTLING LOW-LEVEL ABSTRACTION beware of how much data you send

Slide 60

Slide 60 text

LOW-LEVEL ABSTRACTION send whatever you want ♥ JSON

Slide 61

Slide 61 text

no reconnect no offline detection no encoding/decoding LOW-LEVEL ABSTRACTION handle everything yourself

Slide 62

Slide 62 text

LOW-LEVEL ABSTRACTION the usual patterns

Slide 63

Slide 63 text

Events Use WebSockets for pub/sub between client and server LOW-LEVEL ABSTRACTION the usual patterns

Slide 64

Slide 64 text

Channels Group several events When >1 thing on the socket LOW-LEVEL ABSTRACTION the usual patterns

Slide 65

Slide 65 text

Request/response When you need to ACK a message Or when you’re waiting for a success or error LOW-LEVEL ABSTRACTION the usual patterns

Slide 66

Slide 66 text

Firehose When you want to push EVERYTHING as it’s happening LOW-LEVEL ABSTRACTION the usual patterns

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

Filter streams Register a search query, push when something matches LOW-LEVEL ABSTRACTION the usual patterns

Slide 69

Slide 69 text

or just use it however you want

Slide 70

Slide 70 text

so … what about browsers?

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

” realtime CARE-FREE it’s

Slide 74

Slide 74 text

” realtime CARE-FREE it’s IE 5.5+, Safari 3+, Chrome 4+, Firefox 3+, Opera 10.61+

Slide 75

Slide 75 text

WebSocket Flash Socket Ajax long polling Ajax multipart streaming Forever iframe JSONP polling

Slide 76

Slide 76 text

var io = require('socket.io').listen(8123); io.sockets.on('connection', function(socket) { socket.emit('meetup', { name: 'framsia!' }); socket.on('other-event', function(data) { console.log(data); }); }); BACKEND

Slide 77

Slide 77 text

var socket = io.connect('http://localhost:8123'); socket.on('meetup', function(data) { console.log(data); socket.emit('other-event', { my: 'data' }); }); FRONTEND

Slide 78

Slide 78 text

solves many of the usual problems

Slide 79

Slide 79 text

NO SILVER BULLET however, it’s

Slide 80

Slide 80 text

NO SILVER BULLET however, it’s complexity maintained? new abstraction

Slide 81

Slide 81 text

SockJS a different philosophy

Slide 82

Slide 82 text

SockJS “The API should follow HTML5 Websockets API as closely as possible.” a different philosophy

Slide 83

Slide 83 text

we live in an enterprise world these work in Node.js, but

Slide 84

Slide 84 text

Java & .NET WebSockets in

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

hosted solutions?

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

no definitive choices pros cons &

Slide 92

Slide 92 text

PRODUCTION? is it ready for

Slide 93

Slide 93 text

Check the Origin header Use random tokens and verify on server &

Slide 94

Slide 94 text

when should I use WebSockets?

Slide 95

Slide 95 text

there’s more to it than a FLASHY demo effect

Slide 96

Slide 96 text

Server-Sent Events

Slide 97

Slide 97 text

≈ Streaming – hacks + some good stuff “forever frame”

Slide 98

Slide 98 text

Server-Sent Events Client Server

Slide 99

Slide 99 text

why? Super simple API When you only need push It’s just HTTP

Slide 100

Slide 100 text

var source = new EventSource('/stream'); source.onopen = function(e) { console.log('opened'); } source.addEventListener('open', function(e) { console.log('opened'); }, false); source.addEventListener('message', function(e) { console.log(e.data); }, false); FRONTEND

Slide 101

Slide 101 text

var http = require('http'); var express = require('express'); BACKEND var app = express(); app.use(express.static('./public')); http.createServer(app).listen(8123); app.get('/stream', function(req, res) { req.socket.setTimeout(Infinity); }); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); res.write('\n'); var messageCount = 0; setInterval(function() { messageCount++; res.write('id: ' + messageCount + '\n'); res.write('data: msg ' + messageCount + '\n\n'); }, 1000); res.write('data: testing\n\n');

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

No content

Slide 105

Slide 105 text

Need more than one channel? var source = new EventSource('/stream'); source.addEventListener('message', function(e) { console.log(e.data); }, false); source.addEventListener('userlogon', function(e) { console.log('login', e.data); }, false); REGULAR MESSAGE data: msg 1\n\n WITH EVENT NAME event: userlogon\n data: kimjoar\n\n

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

STOP! source.close(); Stoping the client Stoping the server Return HTTP status code != 200 OK

Slide 108

Slide 108 text

and that’s about it

Slide 109

Slide 109 text

so … what about browsers?

Slide 110

Slide 110 text

No content

Slide 111

Slide 111 text

Server-Sent Events WebSockets Bidirectional & full duplex Better browser-support Handles binary data Automatic reconnect Simpler protocol Just HTTP

Slide 112

Slide 112 text

QUESTIONS?