The request/response model
GET /7020c0e8b09f4314ceee7c0ebccaff3fe956da1820.png HTTP/1.1 Host: new.tinygrab.com Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: image/webp,image/*,*/*;q=0.8 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,ru;q=0.6,uk;q=0.4 Cookie: __utma=80076562.1; __utmc=80076562; __utmz=80076562Total 456 chars. Req/res overhead?
Request every n seconds
setInterval(function() { $.ajax({ url: '/server', dataType: 'json', success: function () { ... } }) }, 30000);Request every 30 seconds the "/server" endpoint
Request every n seconds \w wait-delay
a channel over a single TCP connection ws://
upgrade http to websocket send data frames in both directions end the connection
switching the HTTP protocol to WebSocket
each of client & server becomes as peer
only 2 bytes of overhead no latency for creation new TCP connection no polling overhead (will send message when it needed)
caniuse.com 89.42%
var ws = new WebSocket('ws://echo.websocket.org'); ws.onopen = function() { ws.send('hi'); } ws.onmessage = function(event) { console.log('message %s', event.data) } ws.onclose = function(event) { console.log('closed', event.code) }
Dockerfile:
FROM centos:6 MAINTAINER itspoma <itspoma@gmail.com> RUN yum clean all \ && yum install -y git curl wget mc RUN curl --silent --location https://rpm.nodesource.com/setup | bash - \ && yum install -y nodejs \ && npm install -g npm@latest \ && npm install -g inherits RUN cd /tmp/ && npm install ws \ && wget -O /tmp/server.js http://pastebin.com/raw/cUGe4Bgm
Shell instructions:
$ wget -O Dockerfile http://pastebin.com/raw/0Xn5uZxc $ docker rm -f websocket-container $ docker rmi -f websocket-image $ docker build -t websocket-image . $ docker run --name=websocket-container -p 4871:8080 -tid websocket-image $ docker exec -ti websocket-container bash vm$ node /tmp/server.js vm$ nohup node /tmp/server.js >/dev/null 2>&1 &
var WebSocketServer = require('ws').Server , wss = new WebSocketServer({ port: 8080 }); wss.broadcast = function (data) { wss.clients.forEach(function (client) { client.send(data); }); }; wss.on('connection', function (ws) { console.log('new connection'); ws.on('message', function (message) { console.log('received: %s', message); wss.broadcast(message); }); ws.send('something'); });http://pastebin.com/raw/cUGe4Bgm
var ws = new WebSocket('ws://185.69.152.203:4871'); ws.onopen = function() { ws.send('hi'); } ws.onmessage = function(event) { console.log('message %s', event.data) } ws.onclose = function(event) { console.log('closed', event.code) } ws.send('welcome');http://jsfiddle.net/7hvph2ob/4/
websocket-based DDP (Distributed Data Protocol) to fetch structured data from a server, deliver live updates as data changes, and for remote procedure call