SlideShare a Scribd company logo
Adventures in real-time web applications
Get Real!
Real time?
• In a real time application, all participants
receive content as soon as it is authored.
Party line
IRC
World of Warcraft
Real time is...
• Synchronous
• Social (sometimes)
• Collaborative
• Messy
Dispatched and Controlled
Real time web
• Any real time application that is accessed
via a web browser
Facebook
Twitter
EBS
• Gmail and Chat
• Google docs
• Any real-time feed
(news, stocks, weather,
class availability in registration system,
Lady Gaga’s Twitter feed)
• WebEx, GoTo Meeting, Adobe Connect,
etc. (??)
Others
Building real time web
apps is challenging
• HTTP is stateless
• Request / Response is its favorite song
• Simulating ongoing connection is expensive
• People still use IE
or
“The Wall”
is the
“Hello,World!”
of real time web programming.
of real time web programming.
of real time web programming.
of real time web programming.
of real time web programming.
Hello,Wall!
• Anything typed by anyone is seen by
everyone.
• Simply showing up on the page allows you
to start participating.
• Very low barrier to entry.
• Participants’ messages go to the dispatcher
• Participants need to get new messages
• Everyone has their own copy of the wall
How do people receive
changes to the wall?
• They could ask for them
• They could wait until someone calls
• But how do you call a browser?
• or appear to call
What are the options?
• Polling
• Long polling
• Hanging GET / infinite (forever) iFrame
• Flash Real Time Messaging Protocol (RTMP)
• Web sockets
• Server Sent Events (SSE)
• If all you’ve got is HTTP . . .
• Everything looks like a Request / Response
• This (anti)pattern is probably the most
common unexamined choice for keeping up
with status.
Polling
Polling
setInterval( function ( ) {
var server = ‘http://www.highedwebgetsreal.com’;
$.ajax({ url: server, data: {action: ‘getMessages’},
success: function(data) {
//Update the wall
chatFunctions.writeWall(data.value);
}, dataType: ‘json’}
);
}, 30000);
Polling
• AKAThe long-held connection
• Server programming waits to answer until
it has a meaningful answer
• The client either receives an event or times
out
• A new connection is established immdiately
Long Polling
Long Polling
(function poll() {
var server = ‘http://www.highedwebgetsreal.com’;
$.ajax({ url: server, data: {action: ‘getMessages’},
success: function(data) {
//Update the wall
chatFunctions.writeWall(data.value);
}, dataType: "json", complete: poll }
);
})();
Long polling
• The closest thing to a continuous
connection that HTTP may have to offer
• Leverages the fact that HTTP requests that
return chunked data do not need to
accurately report their size
• Unreliable support in IE
• A HACK!
Hanging GET or
infinite iFrame
infinite iFrame
Infinite iFrame
<iframe src="http://www.highedwebgetsreal.com/endless.html"
style=”position: absolute; left: -9999px;”>
<p>Your browser does not support iFrames.</p>
</iframe>
endless.html:
HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked
23
<script>chatFunctions.writeToWall(‘Jane Bell: Anyone here yet’);</script>
1A
<script>chatFunctions.writeToWall(‘Aurora Smyth: Just got here. Hi!’);</script>
...
The infinite iFrame
• Client-side Flash object establishes stateful
and persistent connection with server
• Web page communicates via Javascript to
and from the Flash object
• Proprietary but fairly robust
Flash RTMP
script type='text/javascript' src='realTimeLib.js'></script>
div id=”wall”></div>
form>
<input type=”text” id='msg' />
<input type=”submit” id=”send” value=”Send” />
/form>
script type="text/javascript">
rtl = new realTimeLib();
rtl.setup({'RTMPrelay': 'RTMPrelay.swf'});
$(“#send”).click( function() {
rtl.send($(“#msg”).value());
});
function postToWall(data) {
// This function is called by rtl object’s swf when it receives a new post
$(“#wall”).append(data);
}
/script>
Flash RTMP
The story so far
• All of these techniques are work-arounds
and compromises
• Leverage side-effects of HTTP protocol and
browser implementations
• I.E. - not based on standards
• (except Flash RMTP, which has been
partially open-sourced by Adobe)
Web Sockets
• Web sockets is a proposal for a standard
that strives to solve the problem of server-
initiated messages to clients
• IETF RFC 6455
• In standards process at W3C
• Already old hat
Another channel
• Web Sockets work by requesting an
upgrade via a standard HTTP request
• The protocol gets changed to Web Socket,
which is a stateful TCP connection over
another port (often 443)
• Both client and server code then listens for
events on the channel and responds
accordingly.
Web sockets
are good listeners
are good listenersvar ws = new WebSocket("ws://www.highedwebgetsreal.com/chat");
ws.onopen = function() {
ws.send("{‘user’:‘David’}");
}
ws.onNewWallPost = function (evt) {
var received_msg = chatFunctions.parseServerEvt(evt.data);
chatFunctions.writeWall(received_msg.post);
}
$(“#sendBtn”).click(function() {
ws.send($(“#msgField”).value());
}
Look familiar?
Ecapsulated and abstracted
graceful degradation
• Several libraries exist that enable
abstracted real time messaging
• They use the best technology available to
the client and fail over to the next best if
its missing
• Use Web Sockets, Flash, long polling,
or forever iFrame, in that order
Server side
• Node.js has become a very popular server
side implementation language
• It’s non-blocking and has a native event-
driven processing model
• It also lends itself to elegant symmetries
between server and client side code
Server side
• Juggernaut,WebSocket-Node and Socket.IO are
well tested Node libraries
• Socket.IO seems most mature and well maintained
• Nodejitsu.com hosts Node that you write
• Any framework that offers request routing works
well
• Ruby has EM-WebSocket, Socket.IO-rack, Cramp,
or just plain old Sinatra
Server side
• There are also services that take care of
the server for you and let you get started
building apps right away.
• Pusher.com is probably the most visible,
and maybe the most mature.
• peerbind.com is an interesting new-comer
Socket.IO Example
/app.js
ar app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
pp.listen(80);
unction handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
o.sockets.on('connection', function (socket) {
socket.on('set_nickname', function (data) {
socket.set('nickname', data, function () {
socket.emit('ready', data);
});
});
socket.on('post', function (data) {
var tmpName = "";
socket.get('nickname', function (err, data) {
tmpName = data;
});
socket.broadcast.emit('share', '<p><strong>' + tmpName + ':</strong> ' + data.msg + '</p>');
socket.emit('share', '<p><strong>(me):</strong> ' + data.msg + '</p>');
});
);
!doctype html>
html>
<head>
<meta charset="utf-8">
<meta charset=utf-8>
<title>Real time chat example</title>
</head>
<body>
<h1>Hello Chat!</h1>
<form id="getNickName">
<label for="nickname">Choose a nickname </label>
<input type="text" name="nickname">
<input type="submit" name="setNickname" value="Set it!">
</form>
</body>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript"
src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta6/handlebars.min.js"></script>
<script id="wallControl" type="text/x-handlebars-template">
<p>User Nickname: {{userNickName}}</p>
<div class="wall" />
<form>
<input type="text" name="msg" />
<input type="submit" name="send" value="send">
</form>
</script>
<script type="text/javascript">
$(document).ready( function() {
var socket = io.connect('/');
$("[name='setNickname']").click(function(event) {
event.preventDefault();
socket.emit("set_nickname", $("[name='nickname']").val());
$("body").append(theWall);
});
socket.on('ready', function (data) {
var theWall = Handlebars.compile($("#wallControl").html());
theWall = theWall({userNickName: data});
$("#getNickName").remove();
$("body").append(theWall);
});
$("[name='send']").live("click", function(event) {
socket.emit("post", { msg: $("[name='msg']").val() });
$("[name='msg']").val("");
event.preventDefault();
});
socket.on('share', function (data) {
$(".wall").append(data);
});
});
</script>
</html>
div class="image">
<div id="canvasDiv"></div>
/div>
p class="demoToolList"><button id="clearCanvas" type="button">Clear</button></p>
unction addClick(x, y, dragging, broadcast) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
if (broadcast) {
socket.emit("addClick", {x: x, y: y, dragging: dragging});
}
ocket.on('reAddClick', function (data) {
addClick(data.x, data.y, data.dragging, false);
);
unction redraw(click_x, click_y, click_drag, broadcast) {
clickX = click_x;
clickY = click_y;
clickDrag = clickDrag;
if (broadcast) {
socket.emit("redraw", {clickX: click_x, clickY: click_y, clickDrag: click_drag});
}
canvas.width = canvas.width; // Clears the canvas
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < click_x.length; i++) {
context.beginPath();
if(click_drag[i] && i){
context.moveTo(click_x[i-1], click_y[i-1]);
}else{
context.moveTo(click_x[i]-1, click_y[i]);
}
context.lineTo(click_x[i], click_y[i]);
context.closePath();
context.stroke();
}
ocket.on('reredraw', function (data) {
redraw(data.clickX, data.clickY, data.clickDrag, false);
);
More feature ideas easily
supported by Socket.IO
• Person to person IM sessions
• Chat rooms
• “Volatile” messages
• Blocking users
• Namespaces to multiplex single connections
Some things are server-sent
Server-Sent Events
(SSE)
• Web Hypertext Application Technology Working Group
(WHATWG)
• Opera was first to provide support in 2006
• Simpler messaging protocol
• No need to upgrade connection - Runs on HTTP/80
• All browsers now support SSE in their current versions
• Except IE (except with EventSource.js polyfill)
// Client-side Javascript
var source = new EventSource('/stream');
source.addEventListener('message', function(e){
console.log('Received a message:', e.data);
});
# Server-side solution using Sinatra
get '/stream', :provides => 'text/event-stream' do
stream :keep_open do |out|
connections << out
out.callback { connections.delete(out) }
end
end
post '/' do
connections.each { |out| out << "data: #{params[:msg]}nn" }
204 # response without entity body
end
David DeMello
ddd1@cornell.edu
@daviddemello
Questions?

More Related Content

What's hot

REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
PiXeL16
 
Connect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick StreuleConnect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick Streule
Atlassian
 
Revoke-Obfuscation
Revoke-ObfuscationRevoke-Obfuscation
Revoke-Obfuscation
Daniel Bohannon
 
Async fun
Async funAsync fun
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
Yevgeniy Brikman
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShellPesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
Daniel Bohannon
 
Collab365: PowerShell for Office 365
Collab365: PowerShell for Office 365Collab365: PowerShell for Office 365
Collab365: PowerShell for Office 365
Vlad Catrinescu
 
Serverless and serverfull - where microservices compliments serverless
Serverless and serverfull - where microservices compliments serverlessServerless and serverfull - where microservices compliments serverless
Serverless and serverfull - where microservices compliments serverless
Judy Breedlove
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
Johan Andrén
 
Server side data sync for mobile apps with silex
Server side data sync for mobile apps with silexServer side data sync for mobile apps with silex
Server side data sync for mobile apps with silex
Michele Orselli
 
Implementing Server Side Data Synchronization for Mobile Apps
Implementing Server Side Data Synchronization for Mobile AppsImplementing Server Side Data Synchronization for Mobile Apps
Implementing Server Side Data Synchronization for Mobile Apps
Michele Orselli
 
PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016
Daniel Peter
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
Implementing data sync apis for mibile apps @cloudconf
Implementing data sync apis for mibile apps @cloudconfImplementing data sync apis for mibile apps @cloudconf
Implementing data sync apis for mibile apps @cloudconf
Michele Orselli
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
Nicholas McClay
 
Designing a beautiful REST json api
Designing a beautiful REST json apiDesigning a beautiful REST json api
Designing a beautiful REST json api
0x07de
 
How to build a scalable SNS via Polling & Push
How to build a scalable SNS via Polling & PushHow to build a scalable SNS via Polling & Push
How to build a scalable SNS via Polling & Push
Mu Chun Wang
 
DevSec Defense
DevSec DefenseDevSec Defense
DevSec Defense
Daniel Bohannon
 
Big data with hadoop Setup on Ubuntu 12.04
Big data with hadoop Setup on Ubuntu 12.04Big data with hadoop Setup on Ubuntu 12.04
Big data with hadoop Setup on Ubuntu 12.04
Mandakini Kumari
 

What's hot (20)

REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
Connect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick StreuleConnect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick Streule
 
Revoke-Obfuscation
Revoke-ObfuscationRevoke-Obfuscation
Revoke-Obfuscation
 
Async fun
Async funAsync fun
Async fun
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShellPesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
PesterSec: Using Pester & ScriptAnalyzer to Detect Obfuscated PowerShell
 
Collab365: PowerShell for Office 365
Collab365: PowerShell for Office 365Collab365: PowerShell for Office 365
Collab365: PowerShell for Office 365
 
Serverless and serverfull - where microservices compliments serverless
Serverless and serverfull - where microservices compliments serverlessServerless and serverfull - where microservices compliments serverless
Serverless and serverfull - where microservices compliments serverless
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
 
Server side data sync for mobile apps with silex
Server side data sync for mobile apps with silexServer side data sync for mobile apps with silex
Server side data sync for mobile apps with silex
 
Implementing Server Side Data Synchronization for Mobile Apps
Implementing Server Side Data Synchronization for Mobile AppsImplementing Server Side Data Synchronization for Mobile Apps
Implementing Server Side Data Synchronization for Mobile Apps
 
PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
Implementing data sync apis for mibile apps @cloudconf
Implementing data sync apis for mibile apps @cloudconfImplementing data sync apis for mibile apps @cloudconf
Implementing data sync apis for mibile apps @cloudconf
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
Designing a beautiful REST json api
Designing a beautiful REST json apiDesigning a beautiful REST json api
Designing a beautiful REST json api
 
How to build a scalable SNS via Polling & Push
How to build a scalable SNS via Polling & PushHow to build a scalable SNS via Polling & Push
How to build a scalable SNS via Polling & Push
 
DevSec Defense
DevSec DefenseDevSec Defense
DevSec Defense
 
Big data with hadoop Setup on Ubuntu 12.04
Big data with hadoop Setup on Ubuntu 12.04Big data with hadoop Setup on Ubuntu 12.04
Big data with hadoop Setup on Ubuntu 12.04
 

Similar to Get Real: Adventures in realtime web apps

A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
GWTcon
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJSJugando con websockets en nodeJS
Jugando con websockets en nodeJS
Israel Gutiérrez
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
Wim Godden
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
Aaron Stannard
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with Scarlet
Zhixuan Lai
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
FITC
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
Arnout Kazemier
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
JUDCon Brazil 2013 - Vert.x an introduction
JUDCon Brazil 2013 - Vert.x an introductionJUDCon Brazil 2013 - Vert.x an introduction
JUDCon Brazil 2013 - Vert.x an introductionSamuel Tauil
 
From Node to Go
From Node to GoFrom Node to Go
From Node to Go
John Maxwell
 
Learn AJAX at ASIT
Learn AJAX at ASITLearn AJAX at ASIT
Learn AJAX at ASIT
ASIT
 

Similar to Get Real: Adventures in realtime web apps (20)

A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJSJugando con websockets en nodeJS
Jugando con websockets en nodeJS
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with Scarlet
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
08 ajax
08 ajax08 ajax
08 ajax
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
JUDCon Brazil 2013 - Vert.x an introduction
JUDCon Brazil 2013 - Vert.x an introductionJUDCon Brazil 2013 - Vert.x an introduction
JUDCon Brazil 2013 - Vert.x an introduction
 
From Node to Go
From Node to GoFrom Node to Go
From Node to Go
 
Learn AJAX at ASIT
Learn AJAX at ASITLearn AJAX at ASIT
Learn AJAX at ASIT
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 

Get Real: Adventures in realtime web apps

  • 1. Adventures in real-time web applications Get Real!
  • 2. Real time? • In a real time application, all participants receive content as soon as it is authored.
  • 4. IRC
  • 6. Real time is... • Synchronous • Social (sometimes) • Collaborative • Messy
  • 8. Real time web • Any real time application that is accessed via a web browser
  • 11. EBS
  • 12. • Gmail and Chat • Google docs • Any real-time feed (news, stocks, weather, class availability in registration system, Lady Gaga’s Twitter feed) • WebEx, GoTo Meeting, Adobe Connect, etc. (??) Others
  • 13. Building real time web apps is challenging • HTTP is stateless • Request / Response is its favorite song • Simulating ongoing connection is expensive • People still use IE
  • 14. or “The Wall” is the “Hello,World!” of real time web programming. of real time web programming. of real time web programming. of real time web programming. of real time web programming.
  • 15. Hello,Wall! • Anything typed by anyone is seen by everyone. • Simply showing up on the page allows you to start participating. • Very low barrier to entry.
  • 16. • Participants’ messages go to the dispatcher • Participants need to get new messages • Everyone has their own copy of the wall
  • 17. How do people receive changes to the wall? • They could ask for them • They could wait until someone calls • But how do you call a browser? • or appear to call
  • 18. What are the options?
  • 19. • Polling • Long polling • Hanging GET / infinite (forever) iFrame • Flash Real Time Messaging Protocol (RTMP) • Web sockets • Server Sent Events (SSE)
  • 20. • If all you’ve got is HTTP . . . • Everything looks like a Request / Response • This (anti)pattern is probably the most common unexamined choice for keeping up with status. Polling
  • 22. setInterval( function ( ) { var server = ‘http://www.highedwebgetsreal.com’; $.ajax({ url: server, data: {action: ‘getMessages’}, success: function(data) { //Update the wall chatFunctions.writeWall(data.value); }, dataType: ‘json’} ); }, 30000); Polling
  • 23. • AKAThe long-held connection • Server programming waits to answer until it has a meaningful answer • The client either receives an event or times out • A new connection is established immdiately Long Polling
  • 25. (function poll() { var server = ‘http://www.highedwebgetsreal.com’; $.ajax({ url: server, data: {action: ‘getMessages’}, success: function(data) { //Update the wall chatFunctions.writeWall(data.value); }, dataType: "json", complete: poll } ); })(); Long polling
  • 26. • The closest thing to a continuous connection that HTTP may have to offer • Leverages the fact that HTTP requests that return chunked data do not need to accurately report their size • Unreliable support in IE • A HACK! Hanging GET or infinite iFrame infinite iFrame
  • 28. <iframe src="http://www.highedwebgetsreal.com/endless.html" style=”position: absolute; left: -9999px;”> <p>Your browser does not support iFrames.</p> </iframe> endless.html: HTTP/1.1 200 OK Content-Type: text/plain Transfer-Encoding: chunked 23 <script>chatFunctions.writeToWall(‘Jane Bell: Anyone here yet’);</script> 1A <script>chatFunctions.writeToWall(‘Aurora Smyth: Just got here. Hi!’);</script> ... The infinite iFrame
  • 29. • Client-side Flash object establishes stateful and persistent connection with server • Web page communicates via Javascript to and from the Flash object • Proprietary but fairly robust Flash RTMP
  • 30. script type='text/javascript' src='realTimeLib.js'></script> div id=”wall”></div> form> <input type=”text” id='msg' /> <input type=”submit” id=”send” value=”Send” /> /form> script type="text/javascript"> rtl = new realTimeLib(); rtl.setup({'RTMPrelay': 'RTMPrelay.swf'}); $(“#send”).click( function() { rtl.send($(“#msg”).value()); }); function postToWall(data) { // This function is called by rtl object’s swf when it receives a new post $(“#wall”).append(data); } /script> Flash RTMP
  • 31. The story so far • All of these techniques are work-arounds and compromises • Leverage side-effects of HTTP protocol and browser implementations • I.E. - not based on standards • (except Flash RMTP, which has been partially open-sourced by Adobe)
  • 32. Web Sockets • Web sockets is a proposal for a standard that strives to solve the problem of server- initiated messages to clients • IETF RFC 6455 • In standards process at W3C • Already old hat
  • 33. Another channel • Web Sockets work by requesting an upgrade via a standard HTTP request • The protocol gets changed to Web Socket, which is a stateful TCP connection over another port (often 443) • Both client and server code then listens for events on the channel and responds accordingly.
  • 34. Web sockets are good listeners are good listenersvar ws = new WebSocket("ws://www.highedwebgetsreal.com/chat"); ws.onopen = function() { ws.send("{‘user’:‘David’}"); } ws.onNewWallPost = function (evt) { var received_msg = chatFunctions.parseServerEvt(evt.data); chatFunctions.writeWall(received_msg.post); } $(“#sendBtn”).click(function() { ws.send($(“#msgField”).value()); }
  • 36.
  • 37. Ecapsulated and abstracted graceful degradation • Several libraries exist that enable abstracted real time messaging • They use the best technology available to the client and fail over to the next best if its missing • Use Web Sockets, Flash, long polling, or forever iFrame, in that order
  • 38. Server side • Node.js has become a very popular server side implementation language • It’s non-blocking and has a native event- driven processing model • It also lends itself to elegant symmetries between server and client side code
  • 39. Server side • Juggernaut,WebSocket-Node and Socket.IO are well tested Node libraries • Socket.IO seems most mature and well maintained • Nodejitsu.com hosts Node that you write • Any framework that offers request routing works well • Ruby has EM-WebSocket, Socket.IO-rack, Cramp, or just plain old Sinatra
  • 40. Server side • There are also services that take care of the server for you and let you get started building apps right away. • Pusher.com is probably the most visible, and maybe the most mature. • peerbind.com is an interesting new-comer
  • 42. /app.js ar app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') pp.listen(80); unction handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); o.sockets.on('connection', function (socket) { socket.on('set_nickname', function (data) { socket.set('nickname', data, function () { socket.emit('ready', data); }); }); socket.on('post', function (data) { var tmpName = ""; socket.get('nickname', function (err, data) { tmpName = data; }); socket.broadcast.emit('share', '<p><strong>' + tmpName + ':</strong> ' + data.msg + '</p>'); socket.emit('share', '<p><strong>(me):</strong> ' + data.msg + '</p>'); }); );
  • 43. !doctype html> html> <head> <meta charset="utf-8"> <meta charset=utf-8> <title>Real time chat example</title> </head> <body> <h1>Hello Chat!</h1> <form id="getNickName"> <label for="nickname">Choose a nickname </label> <input type="text" name="nickname"> <input type="submit" name="setNickname" value="Set it!"> </form> </body> <script type="text/javascript" src="/socket.io/socket.io.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta6/handlebars.min.js"></script> <script id="wallControl" type="text/x-handlebars-template"> <p>User Nickname: {{userNickName}}</p> <div class="wall" /> <form> <input type="text" name="msg" /> <input type="submit" name="send" value="send"> </form> </script>
  • 44. <script type="text/javascript"> $(document).ready( function() { var socket = io.connect('/'); $("[name='setNickname']").click(function(event) { event.preventDefault(); socket.emit("set_nickname", $("[name='nickname']").val()); $("body").append(theWall); }); socket.on('ready', function (data) { var theWall = Handlebars.compile($("#wallControl").html()); theWall = theWall({userNickName: data}); $("#getNickName").remove(); $("body").append(theWall); }); $("[name='send']").live("click", function(event) { socket.emit("post", { msg: $("[name='msg']").val() }); $("[name='msg']").val(""); event.preventDefault(); }); socket.on('share', function (data) { $(".wall").append(data); }); }); </script> </html>
  • 45. div class="image"> <div id="canvasDiv"></div> /div> p class="demoToolList"><button id="clearCanvas" type="button">Clear</button></p> unction addClick(x, y, dragging, broadcast) { clickX.push(x); clickY.push(y); clickDrag.push(dragging); if (broadcast) { socket.emit("addClick", {x: x, y: y, dragging: dragging}); } ocket.on('reAddClick', function (data) { addClick(data.x, data.y, data.dragging, false); ); unction redraw(click_x, click_y, click_drag, broadcast) { clickX = click_x; clickY = click_y; clickDrag = clickDrag; if (broadcast) { socket.emit("redraw", {clickX: click_x, clickY: click_y, clickDrag: click_drag}); } canvas.width = canvas.width; // Clears the canvas context.strokeStyle = "#df4b26"; context.lineJoin = "round"; context.lineWidth = 5; for(var i=0; i < click_x.length; i++) { context.beginPath(); if(click_drag[i] && i){ context.moveTo(click_x[i-1], click_y[i-1]); }else{ context.moveTo(click_x[i]-1, click_y[i]); } context.lineTo(click_x[i], click_y[i]); context.closePath(); context.stroke(); } ocket.on('reredraw', function (data) { redraw(data.clickX, data.clickY, data.clickDrag, false); );
  • 46. More feature ideas easily supported by Socket.IO • Person to person IM sessions • Chat rooms • “Volatile” messages • Blocking users • Namespaces to multiplex single connections
  • 47. Some things are server-sent
  • 48. Server-Sent Events (SSE) • Web Hypertext Application Technology Working Group (WHATWG) • Opera was first to provide support in 2006 • Simpler messaging protocol • No need to upgrade connection - Runs on HTTP/80 • All browsers now support SSE in their current versions • Except IE (except with EventSource.js polyfill)
  • 49. // Client-side Javascript var source = new EventSource('/stream'); source.addEventListener('message', function(e){ console.log('Received a message:', e.data); }); # Server-side solution using Sinatra get '/stream', :provides => 'text/event-stream' do stream :keep_open do |out| connections << out out.callback { connections.delete(out) } end end post '/' do connections.each { |out| out << "data: #{params[:msg]}nn" } 204 # response without entity body end