Scott Mattocks | @scottmattocks | scott@crisscott.com
There shall be no delay in presenting the user with their information.
There shall be no wasted bytes.
Remeber these for later…
The experience for the first 20 users shall be the same as it is for the first 20,000.
function
poll_server
() {new
Ajax
.Request
(this
.urlPolling
, { method:'post'
, parameters:data
, onSuccess:this
.successHandler
, onFailure:this
.handleFailure
, onException:this
.handleException
}); }setInterval
('poll_server()'
,5000
);
This is not realtime communication.
function
poll_server
() {new
Ajax
.Request
(this
.urlPolling
, { method:'post'
, parameters:data
, onSuccess:this
.successHandler
, onFailure:this
.handleFailure
, onException:this
.handleException
}); }function
successHandler
(data
) {// Do something with the data
this
.poll_server
(); }
How do you know when there is new data?
while
(true
) {$data
=$db
->query
($query
);if
($data
) {break
; } }
If this looks like a good idea to you, please leave now.
This is not realtime communication.
We need a way to know when there are updates without polling the database
We can connect to two servers that talk to each other
<?php$query
='INSERT INTO messages VALUES (?, ?)'
;$stmt
=$pdo
->prepare
($query
);$stmt
->prepare
($message
,$date
);$polling_server
->send
($message
); ?>
<?phpforeach
($this
->waiting
as
$connection
) {$connection
->respond
($message
); } ?>
The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling). - WebSocket Protocol
This is realtime communication.
var
ws
=new
WebSocket
(url
);ws
.onopen
=function
() {// Called when the connection opens
};ws
.onmessage
=function
() {// Called when the server sends stuff
};ws
.onclose
=function
() {// Called when the connection is killed
};ws
.send
('Some awesome data'
);// Some time later...
ws
.close
();
GET /demo HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: AQIDBAUGBwgJCgsMDQ4PEC== Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Version: 7
HTTP/1.1 101 Switching Protocols Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Accept: OfS0wDaT5NoxF2gqm7Zj2YtetzM=