3. Chat on a webpage
Requirements:
• Send messages client→server
• Send messages server→client
• Detect when client is connected to server
(“presence”)
4. Traditional HTTP
XMLHttpRequest Long Polling
(HTTP from JavaScript) (Long-running XMLHttpRequest)
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open("POST", "/send"); request.open("GET", "/receive");
request.send("Four times."); request.send();
request.onload = function() {
appendMessage(this.responseText);
startNewRequest();
};
5. 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
6. 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
7. WebSocket JavaScript API
var ws = new WebSocket("wss://host"); var ws = new WebSocket("wss://host");
ws.send("Four times."); ws.onmessage = function(event) {
ws.send("It has to be."); appendMessage(event.data);
};
12. Server application Integration
2. Message Queue / Service API:
Messaging between app and WS server
(Redis-SockJS push-only broker: cargomedia/socket-redis)
Message Queue
Application code Broker
Apache WS Server