Post on 15-Jan-2015
description
WebSocketTwo-way realtime communication for websites
Chat on a webpage
“Four times.” “Four times.”
Chat on a webpage
Requirements:
• Send messages client→server
• Send messages server→client
• Detect when client is connected to server (“presence”)
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();};
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
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
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);};
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
Compatibility
http://caniuse.com/websockets
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)
Server application Integration
1. Same application base:WS-server which reuses your app code
Apache WS Server
Application code
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