SlideShare une entreprise Scribd logo
1  sur  47
Asynchronous Web
Programming with HTML5
WebSockets and Java
James Falkner
Community Manager, Liferay, Inc.
james.falkner@liferay.com
@schtool
The Asynchronous World
The Asynchronous Word
• Literally: Without Time
• Events that occur outside of the main program
execution flow
• Asynchronous != parallel/multi-threading
Execution Models
Execution Models
Single-Threaded Synchronous Model
• Not much to say here
Execution Models
Threaded Model
• CPU controls interleaving
• Developer must
coordinate
threads/processes
• “preemptive multitasking”
Execution Models
Asynchronous Model
• Developer controls interleaving
• “cooperative multitasking”
• Wave goodbye to race conditions,
synchronized, and deadlocks!
• Windows 3.x, MacOS 9.x, Space
Shuttle
Execution Models
The green code (your code!)
runs uninterrupted until it
(you!) reaches a “good
stopping point”
(I/O)
What does this buy me?
NOTHING! Except when
• Task Pool is large
• Task I/O >> Task CPU
• Tasks mostly independent
… Like web servers
Programming Models
Threaded vs. Event-Driven
while (true) {
client = accept(80);
/* blocked! */
new Thread(new Handler(client)).start();
}
vs.
new Server(80, {
onConnect: {
handler.handle(client);
}
});
/* no blocking here, move along */
Threaded vs. Event-Driven
• Both can solve the exact same set of problems
• In fact, they are semantically equivalent
• Threaded costs in complexity and context
switching
• Event-Driven costs in complexity and no
context switching
Forces
• When to consider event-driven, asynchronous
programming models?
Async/Eventing Support
• Hardware/OS: Interrupts, select(), etc
• Languages: callbacks, closures, futures,
promises, Reactor/IOU pattern
• All accomplish the same thing: do this thing
for me, and when you’re done, do this other
dependent thing
• Frameworks
• Makes async/event programming possible or
easier
• JavaEE, Play, Vert.x, Cramp, node.js,
Twisted, …
Reducing Complexity
• Use established patterns
• Use established libraries and tooling
https://github.com/caolan/async
Typical Evented Web Apps
Event-Driven Java/JavaEE
• Java 1.0: Threads and AWT
• Java 1.4: NIO (Non-blocking I/O, nee New I/O)
• J2EE 1.2: JMS
• JavaEE 6: @Asynchronous and CDI
JavaEE 7: WebSockets
• Future: Lambda Expressions (closures)
myButton.addActionListener(ae -> {
System.out.println(ae.getSource());
});
Early Event-Driven Java
• Closure-like listeners (e.g. addActionListener(), handlers)
• Captured “free” variables must be final
• Hogging CPU in listener is bad
• References to this and OuterClass.this
Event-Driven JavaEE
• Servlet 3.0
• Async servlets
• JAX-RS (Jersey)
• Client Async API (via Futures/callbacks)
• Server Async HTTP Requests
• JMS
• Message Redelivery, QoS, scalability, …
• CDI/EJB
• Via @Inject, @Asynchronous and @Observes
JavaEE Example: Event
Definition
public class HelloEvent {
private String msg;
public HelloEvent(String msg) {
msg = msg;
}
public String getMessage() {
return message;
}
}
JavaEE Example: Event
Subscriber
@Stateless
public class HelloListener {
@Asynchronous
public void listen(@Observes HelloEvent helloEvent){
System.out.println("HelloEvent: " + helloEvent);
}
}
JavaEE Example: Event Publish
@Named("messenger”)
@Stateless
public class HelloMessenger {
@Inject Event<HelloEvent> events;
public void hello() {
events.fire(new HelloEvent("from bean " +
System.currentTimeMillis()));
}
}
<h:commandButton
value="Fire!"
action="#{messenger.hello}"/>
JavaEE Example: Async Servlet
JavaEE Example: Async Servlet
Event-Driven Framework: Vert.x
Event-Driven JavaScript
• Not just for the browser
anymore
• It’s cool to like it! (again)
• Language features greatly
aid event-driven
programming
• Many, many frameworks to
aid in better design
The Asynchronous Web
• Goal: Responsive, Interactive sites
• Technique: Push or Pull
• First: Pull
• Request/Response
• AJAX Pull/Poll
• Now: Push
• Long Polling
• Proprietary (e.g. Flash)
• Server-Sent Events (nee HTTP Streaming)
• WebSockets
WebSockets
• Bi-directional, full-duplex TCP connection
• Asynchronous APIs
• Related Standards
• Protocol: IETF RFC 6455
• Browser API: W3C WebSockets JavaScript
API
• Client/Server API: JSR-356 (Java)
• 50+ Implementations, 15+ Languages
• Java, C#, PHP, Python, C/C++, Node, …
Wire Protocol
Wire Protocol
Wire Protocol
• FIN
• Indicates the last frame of a message
• RSV[1-3]
• 0, or extension-specific
• OPCODE
• Frame identifier (continuation, text, close, etc)
• MASK
• Whether the frame is masked
• PAYLOAD LEN
• Length of data
• PAYLOAD DATA
• Extension Data + Application Data
WebSockets Options
• Endpoint identification
• Version negotiation
• Protocol Extensions negotiation
• Application Sub-protocol negotiation
• Security options
Handshake
Java Server API (JSR-356)
• Endpoints represent client/server connection
• Sessions model set of interactions over
Endpoint
• sync/async messages
• Injection
• Custom encoding/decoding
• Configuration options mirror wire protocol
• Binary/Text
• PathParam
• Extensions
Java Server API
@ServerEndpoint("/websocket")
public class MyEndpoint {
private Session session;
@OnOpen
public void open(Session session) {
this.session = session;
}
@OnMessage
public String echoText(String msg) {
return msg;
}
@OnClose
…
@OnError
…
public void sendSomething() {
session.getAsyncRemote()
.sendText(“Boo!”);
}
Client API (JavaScript)
var ws = new WebSocket('ws://host:port/endpoint');
ws.onmessage = function (event) {
console.log('Received text from the server: ' + event.data);
// do something with it
};
ws.onerror = function(event) {
console. log("Uh oh");
};
ws.onopen = function(event) {
// Here we know connection is established,
// so enable the UI to start sending!
};
ws.onclose = function(event) {
// Here the connection is closing (e.g. user is leaving page),
// so stop sending stuff.
};
Client API (Other)
• Non-Browser APIs for C/C++, Java, .NET, Perl,
PHP, Python, C#, and probably others
WebSocket webSocketClient =
new WebSocket("ws://127.0.0.1:911/websocket", "basic");
webSocketClient.OnClose += new EventHandler(webSocketClient_OnClose);
webSocketClient.OnMessage += new
EventHandler<MessageEventArgs>(webSocketClient_OnMessage);
webSocketClient.Connect());
webSocketClient.Send(“HELLO THERE SERVER!”);
webSocketClient.Close();
Browser Support
• Your users don’t care about WebSockets
• Fallback support: jQuery, Vaadin, Atmosphere,
Socket.IO, Play, etc
Demo
WebSocket
ServerEndpoint
JVM
HTTP
WS
Demo Part Deux
WebSocket
ServerEndpoint
JVM
Node
HTTP
HTTP
WS
WebSocket Gotchas
• Using WebSockets in a thread-based system
(e.g. the JVM)
• Sending or receiving data before connection is
established, re-establishing connections
• UTF-8 Encoding
• Extensions, security, masking make debugging
more challenging
WebSocket Issues
• Ephemeral Port Exhaustion
• Evolving interfaces
• Misbehaving Proxies
Acknowledgements
http://cs.brown.edu/courses/cs168/f12/handouts/async.pdf (Execution Models)
http://www.infosecisland.com/blogview/12681-The-WebSocket-Protocol-Past-Travails-To-Be-Avoided.html (problems)
http://lucumr.pocoo.org/2012/9/24/websockets-101/ (more problems)
http://wmarkito.wordpress.com/2012/07/20/cdi-events-synchronous-x-asynchronous/ (cdi examples)
http://blog.arungupta.me/2010/05/totd-139-asynchronous-request-processing-using-servlets-3-0-and-java-ee-6/ (async
servlets)
http://vertx.io (vert.x example)
https://cwiki.apache.org/TUSCANYWIKI/develop-websocket-binding-for-apache-tuscany.html (handshake image)
http://caniuse.com/websockets (browser compat graph)
Asynchronous Web
Programming with HTML5
WebSockets and Java
James Falkner
Community Manager, Liferay, Inc.
james.falkner@liferay.com
@schtool

Contenu connexe

Tendances

Introduction to SAP Gateway and OData
Introduction to SAP Gateway and ODataIntroduction to SAP Gateway and OData
Introduction to SAP Gateway and ODataChris Whealy
 
Productionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerProductionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerEvan Chan
 
Virtual Reference: Bringing the Library to Your Living Room
Virtual Reference: Bringing the Library to Your Living RoomVirtual Reference: Bringing the Library to Your Living Room
Virtual Reference: Bringing the Library to Your Living RoomNCLA-DLG
 
Introduction to Apache Pig
Introduction to Apache PigIntroduction to Apache Pig
Introduction to Apache PigJason Shao
 
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...Databricks
 
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...t_ivanov
 
LOD (linked open data) part 2 lod 구축과 현황
LOD (linked open data) part 2   lod 구축과 현황LOD (linked open data) part 2   lod 구축과 현황
LOD (linked open data) part 2 lod 구축과 현황LiST Inc
 
An Introduction to Information Retrieval and Applications
 An Introduction to Information Retrieval and Applications An Introduction to Information Retrieval and Applications
An Introduction to Information Retrieval and Applications sathish sak
 
SITIST 2015 Dev - Abap on Hana
SITIST 2015 Dev - Abap on HanaSITIST 2015 Dev - Abap on Hana
SITIST 2015 Dev - Abap on Hanasitist
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginsearchbox-com
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsJulien Le Dem
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceDatabricks
 
Introduction to the Data Web, DBpedia and the Life-cycle of Linked Data
Introduction to the Data Web, DBpedia and the Life-cycle of Linked DataIntroduction to the Data Web, DBpedia and the Life-cycle of Linked Data
Introduction to the Data Web, DBpedia and the Life-cycle of Linked DataSören Auer
 
Apache Spark on Kubernetes Anirudh Ramanathan and Tim Chen
Apache Spark on Kubernetes Anirudh Ramanathan and Tim ChenApache Spark on Kubernetes Anirudh Ramanathan and Tim Chen
Apache Spark on Kubernetes Anirudh Ramanathan and Tim ChenDatabricks
 
Web 2.0 and agriculture libraries
Web 2.0 and agriculture librariesWeb 2.0 and agriculture libraries
Web 2.0 and agriculture librariesVivekanand Jain
 
Chap 1 general introduction of information retrieval
Chap 1  general introduction of information retrievalChap 1  general introduction of information retrieval
Chap 1 general introduction of information retrievalMalobe Lottin Cyrille Marcel
 
Information Seeking Behavior
Information Seeking Behavior Information Seeking Behavior
Information Seeking Behavior Dheeraj Negi
 
Systems Analysis and Design | Final Project
Systems Analysis and Design | Final Project Systems Analysis and Design | Final Project
Systems Analysis and Design | Final Project Amber Raiford
 

Tendances (20)

Introduction to SAP Gateway and OData
Introduction to SAP Gateway and ODataIntroduction to SAP Gateway and OData
Introduction to SAP Gateway and OData
 
Productionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job ServerProductionizing Spark and the Spark Job Server
Productionizing Spark and the Spark Job Server
 
Virtual Reference: Bringing the Library to Your Living Room
Virtual Reference: Bringing the Library to Your Living RoomVirtual Reference: Bringing the Library to Your Living Room
Virtual Reference: Bringing the Library to Your Living Room
 
Introduction to Apache Pig
Introduction to Apache PigIntroduction to Apache Pig
Introduction to Apache Pig
 
Introduction to linked data
Introduction to linked dataIntroduction to linked data
Introduction to linked data
 
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...
The Top Five Mistakes Made When Writing Streaming Applications with Mark Grov...
 
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...
The Impact of Columnar File Formats on SQL-on-Hadoop Engine Performance: A St...
 
LOD (linked open data) part 2 lod 구축과 현황
LOD (linked open data) part 2   lod 구축과 현황LOD (linked open data) part 2   lod 구축과 현황
LOD (linked open data) part 2 lod 구축과 현황
 
An Introduction to Information Retrieval and Applications
 An Introduction to Information Retrieval and Applications An Introduction to Information Retrieval and Applications
An Introduction to Information Retrieval and Applications
 
SITIST 2015 Dev - Abap on Hana
SITIST 2015 Dev - Abap on HanaSITIST 2015 Dev - Abap on Hana
SITIST 2015 Dev - Abap on Hana
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analytics
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
DBpedia InsideOut
DBpedia InsideOutDBpedia InsideOut
DBpedia InsideOut
 
Introduction to the Data Web, DBpedia and the Life-cycle of Linked Data
Introduction to the Data Web, DBpedia and the Life-cycle of Linked DataIntroduction to the Data Web, DBpedia and the Life-cycle of Linked Data
Introduction to the Data Web, DBpedia and the Life-cycle of Linked Data
 
Apache Spark on Kubernetes Anirudh Ramanathan and Tim Chen
Apache Spark on Kubernetes Anirudh Ramanathan and Tim ChenApache Spark on Kubernetes Anirudh Ramanathan and Tim Chen
Apache Spark on Kubernetes Anirudh Ramanathan and Tim Chen
 
Web 2.0 and agriculture libraries
Web 2.0 and agriculture librariesWeb 2.0 and agriculture libraries
Web 2.0 and agriculture libraries
 
Chap 1 general introduction of information retrieval
Chap 1  general introduction of information retrievalChap 1  general introduction of information retrieval
Chap 1 general introduction of information retrieval
 
Information Seeking Behavior
Information Seeking Behavior Information Seeking Behavior
Information Seeking Behavior
 
Systems Analysis and Design | Final Project
Systems Analysis and Design | Final Project Systems Analysis and Design | Final Project
Systems Analysis and Design | Final Project
 

En vedette

Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsNaresh Chintalcheru
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with javaJeongHun Byeon
 
Testing concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer AroraTesting concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer AroraIndicThreads
 
Servlet Async I/O Proposal (NIO.2)
Servlet Async I/O Proposal (NIO.2)Servlet Async I/O Proposal (NIO.2)
Servlet Async I/O Proposal (NIO.2)jfarcand
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketMauricio "Maltron" Leal
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketbrent bucci
 
Quize on scripting shell
Quize on scripting shellQuize on scripting shell
Quize on scripting shelllebse123
 
Shell Scripting With Arguments
Shell Scripting With ArgumentsShell Scripting With Arguments
Shell Scripting With ArgumentsAlex Shaw III
 
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Joachim Jacob
 
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol SupportCloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol SupportVMware Tanzu
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSocketsWASdev Community
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureColin Mackay
 
Bash shell
Bash shellBash shell
Bash shellxylas121
 
From Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSocketsFrom Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSocketsAlessandro Alinone
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting BasicsDr.Ravi
 
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...Codemotion
 

En vedette (20)

Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
Testing concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer AroraTesting concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer Arora
 
JUG louvain websockets
JUG louvain websocketsJUG louvain websockets
JUG louvain websockets
 
Servlet Async I/O Proposal (NIO.2)
Servlet Async I/O Proposal (NIO.2)Servlet Async I/O Proposal (NIO.2)
Servlet Async I/O Proposal (NIO.2)
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
 
Think async
Think asyncThink async
Think async
 
Quize on scripting shell
Quize on scripting shellQuize on scripting shell
Quize on scripting shell
 
Shell Scripting With Arguments
Shell Scripting With ArgumentsShell Scripting With Arguments
Shell Scripting With Arguments
 
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
 
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol SupportCloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Bash shell
Bash shellBash shell
Bash shell
 
From Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSocketsFrom Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSockets
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
 

Similaire à Asynchronous Web Programming with HTML5 WebSockets and Java

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
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 WhenFITC
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationStuart (Pid) Williams
 
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 serializationGWTcon
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
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 ScalaYevgeniy Brikman
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileAmazon Web Services Japan
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Real world #microservices with Apache Camel, Fabric8, and OpenShift
Real world #microservices with Apache Camel, Fabric8, and OpenShiftReal world #microservices with Apache Camel, Fabric8, and OpenShift
Real world #microservices with Apache Camel, Fabric8, and OpenShiftChristian Posta
 
Real-world #microservices with Apache Camel, Fabric8, and OpenShift
Real-world #microservices with Apache Camel, Fabric8, and OpenShiftReal-world #microservices with Apache Camel, Fabric8, and OpenShift
Real-world #microservices with Apache Camel, Fabric8, and OpenShiftChristian Posta
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkVijay Nair
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
What’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new StrategyWhat’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new StrategyMohamed Taman
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 

Similaire à Asynchronous Web Programming with HTML5 WebSockets and Java (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
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
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
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
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
MeteorJS Introduction
MeteorJS IntroductionMeteorJS Introduction
MeteorJS Introduction
 
Scalable io in java
Scalable io in javaScalable io in java
Scalable io in java
 
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
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
Windows 8 Apps and the Outside World
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Real world #microservices with Apache Camel, Fabric8, and OpenShift
Real world #microservices with Apache Camel, Fabric8, and OpenShiftReal world #microservices with Apache Camel, Fabric8, and OpenShift
Real world #microservices with Apache Camel, Fabric8, and OpenShift
 
Real-world #microservices with Apache Camel, Fabric8, and OpenShift
Real-world #microservices with Apache Camel, Fabric8, and OpenShiftReal-world #microservices with Apache Camel, Fabric8, and OpenShift
Real-world #microservices with Apache Camel, Fabric8, and OpenShift
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
What’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new StrategyWhat’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new Strategy
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 

Dernier

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Dernier (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Asynchronous Web Programming with HTML5 WebSockets and Java

  • 1. Asynchronous Web Programming with HTML5 WebSockets and Java James Falkner Community Manager, Liferay, Inc. james.falkner@liferay.com @schtool
  • 3. The Asynchronous Word • Literally: Without Time • Events that occur outside of the main program execution flow • Asynchronous != parallel/multi-threading
  • 5. Execution Models Single-Threaded Synchronous Model • Not much to say here
  • 6. Execution Models Threaded Model • CPU controls interleaving • Developer must coordinate threads/processes • “preemptive multitasking”
  • 7. Execution Models Asynchronous Model • Developer controls interleaving • “cooperative multitasking” • Wave goodbye to race conditions, synchronized, and deadlocks! • Windows 3.x, MacOS 9.x, Space Shuttle
  • 8. Execution Models The green code (your code!) runs uninterrupted until it (you!) reaches a “good stopping point” (I/O)
  • 9. What does this buy me? NOTHING! Except when • Task Pool is large • Task I/O >> Task CPU • Tasks mostly independent … Like web servers
  • 10.
  • 12. Threaded vs. Event-Driven while (true) { client = accept(80); /* blocked! */ new Thread(new Handler(client)).start(); } vs. new Server(80, { onConnect: { handler.handle(client); } }); /* no blocking here, move along */
  • 13. Threaded vs. Event-Driven • Both can solve the exact same set of problems • In fact, they are semantically equivalent • Threaded costs in complexity and context switching • Event-Driven costs in complexity and no context switching
  • 14. Forces • When to consider event-driven, asynchronous programming models?
  • 15. Async/Eventing Support • Hardware/OS: Interrupts, select(), etc • Languages: callbacks, closures, futures, promises, Reactor/IOU pattern • All accomplish the same thing: do this thing for me, and when you’re done, do this other dependent thing • Frameworks • Makes async/event programming possible or easier • JavaEE, Play, Vert.x, Cramp, node.js, Twisted, …
  • 16. Reducing Complexity • Use established patterns • Use established libraries and tooling https://github.com/caolan/async
  • 18. Event-Driven Java/JavaEE • Java 1.0: Threads and AWT • Java 1.4: NIO (Non-blocking I/O, nee New I/O) • J2EE 1.2: JMS • JavaEE 6: @Asynchronous and CDI JavaEE 7: WebSockets • Future: Lambda Expressions (closures) myButton.addActionListener(ae -> { System.out.println(ae.getSource()); });
  • 19. Early Event-Driven Java • Closure-like listeners (e.g. addActionListener(), handlers) • Captured “free” variables must be final • Hogging CPU in listener is bad • References to this and OuterClass.this
  • 20. Event-Driven JavaEE • Servlet 3.0 • Async servlets • JAX-RS (Jersey) • Client Async API (via Futures/callbacks) • Server Async HTTP Requests • JMS • Message Redelivery, QoS, scalability, … • CDI/EJB • Via @Inject, @Asynchronous and @Observes
  • 21. JavaEE Example: Event Definition public class HelloEvent { private String msg; public HelloEvent(String msg) { msg = msg; } public String getMessage() { return message; } }
  • 22. JavaEE Example: Event Subscriber @Stateless public class HelloListener { @Asynchronous public void listen(@Observes HelloEvent helloEvent){ System.out.println("HelloEvent: " + helloEvent); } }
  • 23. JavaEE Example: Event Publish @Named("messenger”) @Stateless public class HelloMessenger { @Inject Event<HelloEvent> events; public void hello() { events.fire(new HelloEvent("from bean " + System.currentTimeMillis())); } } <h:commandButton value="Fire!" action="#{messenger.hello}"/>
  • 27. Event-Driven JavaScript • Not just for the browser anymore • It’s cool to like it! (again) • Language features greatly aid event-driven programming • Many, many frameworks to aid in better design
  • 28. The Asynchronous Web • Goal: Responsive, Interactive sites • Technique: Push or Pull • First: Pull • Request/Response • AJAX Pull/Poll • Now: Push • Long Polling • Proprietary (e.g. Flash) • Server-Sent Events (nee HTTP Streaming) • WebSockets
  • 29.
  • 30. WebSockets • Bi-directional, full-duplex TCP connection • Asynchronous APIs • Related Standards • Protocol: IETF RFC 6455 • Browser API: W3C WebSockets JavaScript API • Client/Server API: JSR-356 (Java) • 50+ Implementations, 15+ Languages • Java, C#, PHP, Python, C/C++, Node, …
  • 33. Wire Protocol • FIN • Indicates the last frame of a message • RSV[1-3] • 0, or extension-specific • OPCODE • Frame identifier (continuation, text, close, etc) • MASK • Whether the frame is masked • PAYLOAD LEN • Length of data • PAYLOAD DATA • Extension Data + Application Data
  • 34. WebSockets Options • Endpoint identification • Version negotiation • Protocol Extensions negotiation • Application Sub-protocol negotiation • Security options
  • 36. Java Server API (JSR-356) • Endpoints represent client/server connection • Sessions model set of interactions over Endpoint • sync/async messages • Injection • Custom encoding/decoding • Configuration options mirror wire protocol • Binary/Text • PathParam • Extensions
  • 37. Java Server API @ServerEndpoint("/websocket") public class MyEndpoint { private Session session; @OnOpen public void open(Session session) { this.session = session; } @OnMessage public String echoText(String msg) { return msg; } @OnClose … @OnError … public void sendSomething() { session.getAsyncRemote() .sendText(“Boo!”); }
  • 38. Client API (JavaScript) var ws = new WebSocket('ws://host:port/endpoint'); ws.onmessage = function (event) { console.log('Received text from the server: ' + event.data); // do something with it }; ws.onerror = function(event) { console. log("Uh oh"); }; ws.onopen = function(event) { // Here we know connection is established, // so enable the UI to start sending! }; ws.onclose = function(event) { // Here the connection is closing (e.g. user is leaving page), // so stop sending stuff. };
  • 39. Client API (Other) • Non-Browser APIs for C/C++, Java, .NET, Perl, PHP, Python, C#, and probably others WebSocket webSocketClient = new WebSocket("ws://127.0.0.1:911/websocket", "basic"); webSocketClient.OnClose += new EventHandler(webSocketClient_OnClose); webSocketClient.OnMessage += new EventHandler<MessageEventArgs>(webSocketClient_OnMessage); webSocketClient.Connect()); webSocketClient.Send(“HELLO THERE SERVER!”); webSocketClient.Close();
  • 40. Browser Support • Your users don’t care about WebSockets • Fallback support: jQuery, Vaadin, Atmosphere, Socket.IO, Play, etc
  • 41.
  • 44. WebSocket Gotchas • Using WebSockets in a thread-based system (e.g. the JVM) • Sending or receiving data before connection is established, re-establishing connections • UTF-8 Encoding • Extensions, security, masking make debugging more challenging
  • 45. WebSocket Issues • Ephemeral Port Exhaustion • Evolving interfaces • Misbehaving Proxies
  • 46. Acknowledgements http://cs.brown.edu/courses/cs168/f12/handouts/async.pdf (Execution Models) http://www.infosecisland.com/blogview/12681-The-WebSocket-Protocol-Past-Travails-To-Be-Avoided.html (problems) http://lucumr.pocoo.org/2012/9/24/websockets-101/ (more problems) http://wmarkito.wordpress.com/2012/07/20/cdi-events-synchronous-x-asynchronous/ (cdi examples) http://blog.arungupta.me/2010/05/totd-139-asynchronous-request-processing-using-servlets-3-0-and-java-ee-6/ (async servlets) http://vertx.io (vert.x example) https://cwiki.apache.org/TUSCANYWIKI/develop-websocket-binding-for-apache-tuscany.html (handshake image) http://caniuse.com/websockets (browser compat graph)
  • 47. Asynchronous Web Programming with HTML5 WebSockets and Java James Falkner Community Manager, Liferay, Inc. james.falkner@liferay.com @schtool