Web apps need to communicate with the server in real-time
...sort of
Full credit for the following diagrams goes to Tieme from his post on StackOverflow
Client sends AJAX request to server, server responds
Client sends AJAX request to server, server keeps request open until response available
Client immediately sends another long-poll request after receiving response
(also see Comet)
Client opens connection with server
Server sends data to client as it becomes available
Client opens connection with server
Client and server send data to each other as data becomes available on either side
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
*WebSocket protocol handshake via Wikipedia.
Allows bi-directional communication over standard HTTP ports
(great for existing servers, proxies, and firewalls, which open 80 & 443)
Defines new protocols, ws://
and wss://
for standard and secure WebSocket connections
Rest of WebSockets URI follows standard URI scheme
var connection = new WebSocket('ws://subdomain.examnple.com/some-endpoint')
connection.onopen = function(e) {
console.log("Connected");
};
connection.onmessage = function(e) {
console.log( "Received: " + e.data);
};
connection.onclose = function(e) {
console.log("Connection closed");
};
WebSockets is cross-domain by default
Up to you to optionally restrict domain access on server via Origin
header
GET ws://echo.websocket.org/?encoding=text HTTP/1.1
Origin: http://websocket.org
Cookie: __utma=99as
Connection: Upgrade
Host: echo.websocket.org
Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==
Upgrade: websocket
Sec-WebSocket-Version: 13
HTTP/1.1 101 WebSocket Protocol Handshake
Date: Fri, 10 Feb 2012 17:38:18 GMT
Connection: Upgrade
Server: Kaazing Gateway
Upgrade: WebSocket
Access-Control-Allow-Origin: http://websocket.org
Access-Control-Allow-Credentials: true
Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=
Access-Control-Allow-Headers: content-type
*WebSocket protocol handshake via websocket.org.
Built-in method for defining WebSocket extensions via RFC
Current extensions include perframe-deflate and multiplexing
var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
(See currently defined subprotocols)
Original WebSocket spec allowed for strings
Now also allows buffered arrays and blobs
connection.send('your message');
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
binary[i] = img.data[i];
}
connection.send(binary.buffer);
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);
(brain-dump)
Doesn't support sending/receiving JSON (yet)
Can be accomplished by serializing/deserializing
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.send(JSON.stringify({
attribute: 'connected'
}));
});
connection.onmessage = function (e) {
var response = JSON.parse(e.data);
};
Not really meant for server-to-server communication; better off using UDP or some other low-overhead transfer protocol if you control both servers
Not meant for browser-to-browser communication; that's what WebRTC is for
Using ws
in production can cause WebSockets communication to fail due to invisible proxies that can't do WebSockets
Using wss
forces browser to issue HTTP_CONNECT
statement to proxy server, which sets up tunnel
So use wss
in production
Initial HTTP handshake to server requests WebSocket upgrade
Server upgrades connection if it knows how
Support can be added to most servers (modules exist for Nginx, Apache, etc.)
Server can be built in any language, which supports event loop
Libraries exist for many languages, including Node, Ruby, Python, PHP, etc. (see list of libraries via Wikipedia)
All modern browsers (including IE10 support WebSockets)
Except Android Browser (but supported in Mobile Chrome, avail on Android >= 4.0, default on Android >= 4.2)
Server and client-side implementation (for Node on server side)
Abstracts WebSocket communications to automatically fall back to flash streaming or long-polling when necessary (on either server or client)
Adds features like heartbeats, timeouts, and disconnection support not provided in WebSocket API