WebSocket

13
WebSocket Two-way realtime communication for websites

description

Introduction on WebSocket. For Webilea on 2013-02-06: http://www.meetup.com/webilea/events/101312452/

Transcript of WebSocket

Page 1: WebSocket

WebSocketTwo-way realtime communication for websites

Page 2: WebSocket

Chat on a webpage

“Four times.” “Four times.”

Page 3: WebSocket

Chat on a webpage

Requirements:

• Send messages client→server

• Send messages server→client

• Detect when client is connected to server (“presence”)

Page 4: WebSocket

Traditional HTTP

XMLHttpRequest(HTTP from JavaScript)

var request = new XMLHttpRequest();request.open("POST", "/send");request.send("Four times.");

Long Polling(Long-running XMLHttpRequest)

var request = new XMLHttpRequest();request.open("GET", "/receive");request.send();request.onload = function() { appendMessage(this.responseText); startNewRequest();};

Page 5: WebSocket

Other techniques and problems

• Long-polling HTTP requests: XHR, script-tag

• Streaming HTTP request: XHR, iframe

• Using rtmp with Flash

• Misuse of HTTP (proxies, browsers, servers)

• Performance (network, httpd cpu)

• Not supported in all browsers

Page 6: WebSocket

WebSocket

• Full-duplex persistent connection over TCP

• Designed by W3C for the web (RFC Dec. ’11)

• Uses port 80

• Handshake features HTTP’s “Upgrade”-header

• The TLS version passes some HTTP-proxies

• Ping/pong frames for staying alive

Page 7: WebSocket

WebSocket JavaScript API

var ws = new WebSocket("wss://host");ws.send("Four times.");ws.send("It has to be.");

var ws = new WebSocket("wss://host");ws.onmessage = function(event) { appendMessage(event.data);};

Page 8: WebSocket

Demo

├── README.md├── client-sockjs│   ├── chat.js│   └── index.html├── client-websocket│   ├── chat.js│   └── index.html└── server ├── package.json └── server.js

https://github.com/njam/websocket-demo-chat

Page 9: WebSocket

Compatibility

http://caniuse.com/websockets

Page 10: WebSocket

Emulation

• WebSocket-like client-API plus server

• Enables realtime-comm. in most used browsers

• SockJS: Node.js, Erlang, Ruby, Python, ..

• Socket.IO: Node.js, Java, Erlang, PHP, .......

• Ratchet: PHP

• APE (C), Atmosphere (Java), Tambur.io (WS), Pusher (WS)

Page 11: WebSocket

Server application Integration

1. Same application base:WS-server which reuses your app code

Apache WS Server

Application code

Page 12: WebSocket

Server application Integration

2. Message Queue / Service API:Messaging between app and WS server(Redis-SockJS push-only broker: cargomedia/socket-redis)

Apache WS Server

Application code BrokerMessage Queue