SlideShare a Scribd company logo
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
Asynchronous Web Programming with HTML5 WebSockets and Java
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
Asynchronous Web Programming with HTML5 WebSockets and Java
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
Asynchronous Web Programming with HTML5 WebSockets and Java
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
Ad

Recommended

Nmap 9つの真実
Nmap 9つの真実
abend_cve_9999_0001
 
AWS 스토리지 마이그레이션 서비스 및 대규모 데이터 전송 사례- 김용기, AWS솔루션즈 아키텍트:: AWS Summit Online K...
AWS 스토리지 마이그레이션 서비스 및 대규모 데이터 전송 사례- 김용기, AWS솔루션즈 아키텍트:: AWS Summit Online K...
Amazon Web Services Korea
 
C++과 Lua script연동
C++과 Lua script연동
선협 이
 
LXC入門 - Osc2011 nagoya
LXC入門 - Osc2011 nagoya
Masahide Yamamoto
 
Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
petabridge
 
Kibanaでsysstatを可視化する
Kibanaでsysstatを可視化する
Kensuke Maeda
 
인생은 짧아요, 엑셀 대신 파이썬
인생은 짧아요, 엑셀 대신 파이썬
Seung-June Lee
 
1. 아키텍쳐 설계 프로세스
1. 아키텍쳐 설계 프로세스
Terry Cho
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
SangIn Choung
 
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Yoichi Kawasaki
 
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
강 민우
 
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
AWSKRUG - AWS한국사용자모임
 
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Web Services Korea
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
Terry Cho
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
Joris Kuipers
 
openstackの仮想マシンHA機能の現状と今後の方向性
openstackの仮想マシンHA機能の現状と今後の方向性
Sampath Priyankara
 
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
Amazon Web Services Korea
 
성능 최대화를 위한 CloudFront 설정 Best Practice
성능 최대화를 위한 CloudFront 설정 Best Practice
GS Neotek
 
How do you measure value?
How do you measure value?
Thoughtworks
 
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
Amazon Web Services Korea
 
Azure ML Training - Deep Dive
Azure ML Training - Deep Dive
Venkatesh Narayanan
 
Serverless, The Middy Way - Workshop
Serverless, The Middy Way - Workshop
Luciano Mammino
 
Windows system - memory개념잡기
Windows system - memory개념잡기
ChangKyu Song
 
AllwinnerタブレットのOSを作ってみる(中編)
AllwinnerタブレットのOSを作ってみる(中編)
shimadah
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
Seongyun Byeon
 
안정적인 서비스 운영 2014.03
안정적인 서비스 운영 2014.03
Changyol BAEK
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Realtime web application with java
Realtime web application with java
JeongHun Byeon
 

More Related Content

What's hot (20)

인생은 짧아요, 엑셀 대신 파이썬
인생은 짧아요, 엑셀 대신 파이썬
Seung-June Lee
 
1. 아키텍쳐 설계 프로세스
1. 아키텍쳐 설계 프로세스
Terry Cho
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
SangIn Choung
 
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Yoichi Kawasaki
 
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
강 민우
 
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
AWSKRUG - AWS한국사용자모임
 
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Web Services Korea
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
Terry Cho
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
Joris Kuipers
 
openstackの仮想マシンHA機能の現状と今後の方向性
openstackの仮想マシンHA機能の現状と今後の方向性
Sampath Priyankara
 
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
Amazon Web Services Korea
 
성능 최대화를 위한 CloudFront 설정 Best Practice
성능 최대화를 위한 CloudFront 설정 Best Practice
GS Neotek
 
How do you measure value?
How do you measure value?
Thoughtworks
 
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
Amazon Web Services Korea
 
Azure ML Training - Deep Dive
Azure ML Training - Deep Dive
Venkatesh Narayanan
 
Serverless, The Middy Way - Workshop
Serverless, The Middy Way - Workshop
Luciano Mammino
 
Windows system - memory개념잡기
Windows system - memory개념잡기
ChangKyu Song
 
AllwinnerタブレットのOSを作ってみる(中編)
AllwinnerタブレットのOSを作ってみる(中編)
shimadah
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
Seongyun Byeon
 
안정적인 서비스 운영 2014.03
안정적인 서비스 운영 2014.03
Changyol BAEK
 
인생은 짧아요, 엑셀 대신 파이썬
인생은 짧아요, 엑셀 대신 파이썬
Seung-June Lee
 
1. 아키텍쳐 설계 프로세스
1. 아키텍쳐 설계 프로세스
Terry Cho
 
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
[기본과정] 코드 테스트와 커버리지 기본 교육(개념)
SangIn Choung
 
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Web App for Containers + MySQLでコンテナ対応したPHPアプリを作ろう!
Yoichi Kawasaki
 
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
[IGC] 엔씨소프트 이경종 - 강화 학습을 이용한 NPC AI 구현
강 민우
 
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
AWSKRUG - AWS한국사용자모임
 
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Elastcsearch Service 소개 및 활용 방법 (윤석찬)
Amazon Web Services Korea
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
Terry Cho
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
Joris Kuipers
 
openstackの仮想マシンHA機能の現状と今後の方向性
openstackの仮想マシンHA機能の現状と今後の方向性
Sampath Priyankara
 
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
Amazon Web Services Korea
 
성능 최대화를 위한 CloudFront 설정 Best Practice
성능 최대화를 위한 CloudFront 설정 Best Practice
GS Neotek
 
How do you measure value?
How do you measure value?
Thoughtworks
 
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
CJ프레시웨이 All-in 클라우드 전환 사례를 통해서 알아보는 Modernization성공 사례-오동규, 메가존 인프라 모더나이제이션 그...
Amazon Web Services Korea
 
Serverless, The Middy Way - Workshop
Serverless, The Middy Way - Workshop
Luciano Mammino
 
Windows system - memory개념잡기
Windows system - memory개념잡기
ChangKyu Song
 
AllwinnerタブレットのOSを作ってみる(中編)
AllwinnerタブレットのOSを作ってみる(中編)
shimadah
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
Seongyun Byeon
 
안정적인 서비스 운영 2014.03
안정적인 서비스 운영 2014.03
Changyol BAEK
 

Viewers also liked (20)

Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Realtime web application with java
Realtime web application with java
JeongHun Byeon
 
Testing concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer Arora
IndicThreads
 
JUG louvain websockets
JUG louvain websockets
Marc Tritschler
 
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 WebSocket
Mauricio "Maltron" Leal
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
brent bucci
 
Think async
Think async
Bhakti Mehta
 
Quize on scripting shell
Quize on scripting shell
lebse123
 
Shell Scripting With Arguments
Shell Scripting With Arguments
Alex 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...
Joachim Jacob
 
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
VMware Tanzu
 
Introduction to WebSockets
Introduction to WebSockets
WASdev Community
 
Bash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
Shell Scripting
Shell Scripting
Gaurav Shinde
 
Bash shell
Bash shell
xylas121
 
From Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSockets
Alessandro Alinone
 
Unix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Codemotion
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Realtime web application with java
Realtime web application with java
JeongHun Byeon
 
Testing concurrent java programs - Sameer Arora
Testing concurrent java programs - Sameer Arora
IndicThreads
 
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 WebSocket
Mauricio "Maltron" Leal
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
brent bucci
 
Quize on scripting shell
Quize on scripting shell
lebse123
 
Shell Scripting With Arguments
Shell Scripting With Arguments
Alex 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...
Joachim Jacob
 
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
Cloud Foundry Summit 2015: Cloud Foundry and IoT Protocol Support
VMware Tanzu
 
Introduction to WebSockets
Introduction to WebSockets
WASdev Community
 
Bash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
Bash shell
Bash shell
xylas121
 
From Push Technology to Real-Time Messaging and WebSockets
From Push Technology to Real-Time Messaging and WebSockets
Alessandro Alinone
 
Unix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...
Codemotion
 
Ad

Similar to Asynchronous Web Programming with HTML5 WebSockets and Java (20)

Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Codemotion
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
jaxconf
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7
Lukáš Fryč
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
WebStackAcademy
 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
C2B2 Consulting
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
 
WebSockets in JEE 7
WebSockets in JEE 7
Shahzad Badar
 
Lecture 6 Web Sockets
Lecture 6 Web Sockets
Fahad Golra
 
Don't Wait! Develop responsive applications with Java EE7 instead
Don't Wait! Develop responsive applications with Java EE7 instead
Erin Schnabel
 
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
 
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Srikanth Reddy Pallerla
 
Java adv
Java adv
Balakumaran Arunachalam
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Codemotion
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
jaxconf
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
 
WebSockets - Realtime em Mundo Conectado
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7
Lukáš Fryč
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
jaxLondonConference
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
WebSocket in Enterprise Applications 2015
WebSocket in Enterprise Applications 2015
Pavel Bucek
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
WebStackAcademy
 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
C2B2 Consulting
 
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Java API for WebSocket 1.0: Java EE 7 and GlassFish
Arun Gupta
 
Lecture 6 Web Sockets
Lecture 6 Web Sockets
Fahad Golra
 
Don't Wait! Develop responsive applications with Java EE7 instead
Don't Wait! Develop responsive applications with Java EE7 instead
Erin Schnabel
 
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
 
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Srikanth Reddy Pallerla
 
Ad

Recently uploaded (20)

"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 

Asynchronous Web Programming with HTML5 WebSockets and Java

  • 1. Asynchronous Web Programming with HTML5 WebSockets and Java James Falkner Community Manager, Liferay, Inc. [email protected] @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
  • 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
  • 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
  • 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. [email protected] @schtool