SlideShare una empresa de Scribd logo
1 de 43
1

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations
/asynchronous-event-websocket

InfoQ.com: News & Community Site
• 750,000 unique visitors/month
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• News 15-20 / week
• Articles 3-4 / week
• Presentations (videos) 12-15 / week
• Interviews 2-3 / week
• Books 1 / month
Presented at QCon New York
www.qconnewyork.com
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Building Java
HTML5/WebSocket
Applications with JSR 356
Reza Rahman
Java EE/GlassFish Evangelist
Reza.Rahman@Oracle.com
@reza_rahman
Program Agenda

 WebSocket Primer

 JSR 356: Java API for WebSocket
 Demo

3

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Interactive Web Sites
 HTTP is half-duplex
 Flavors of Server Push
– Polling
– Long Polling

– Comet/Ajax

 Complex, Inefficient, Wasteful

4

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
WebSocket to the Rescue
 TCP based, bi-directional, full-duplex messaging
 Originally proposed as part of HTML5
 IETF-defined Protocol: RFC 6455
 W3C defined JavaScript API

5

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
What’s the basic idea ?
 Establish connection (Single TCP connection)
 Send messages in both direction (Bi-directional)
 Send message independent of each other (Full Duplex)
 End connection

6

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Establish a connection

Handshake Request

Client

Server
Handshake Response

7

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Handshake Request
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

8

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Handshake Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

9

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Establishing a Connection

Handshake Request

Client

Server
Handshake Response

Connected !

10

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
WebSocket Lifecycle
Connected !

open

open

message

Client

message

error
message

Server
message

close

Disconnected

11

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
WebSocket API
www.w3.org/TR/websockets/

12

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Java WebSocket Implementations
Java-WebSocket
Grizzly

WebSocket SDK

Apache Tomcat 7

Webbit

GlassFish

Atmosphere

Autobahn

websockets4j

WeberKnecht

GNU WebSocket4J

Jetty

Netty

JBoss

TorqueBox

Caucho Resin

SwaggerSocket

jWebSocket

13

Kaazing WebSocket Gateway

jWamp

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Browser Support

14

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
JSR 356: Java API for Web Socket
 Specification
– http://jcp.org/en/jsr/detail?id=356
– http://java.net/projects/websocket-spec
– Included in Java EE 7

 Reference Implementation
– http://java.net/projects/tyrus

– Bundled with Glassfish 4

15

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Java API for WebSocket Features
 Create WebSocket Endpoints
– Interface-driven (Endpoint)
– Annotation-driven (@ServerEndpoint)

 Client and server APIs
 SPI for extensions and data frames

16

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Basic API Tour

17

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Hello World Server
public class HelloServer extends Endpoint {
@Override
public void onOpen(Session session,
EndpointConfig configuration) {
session.addMessageHandler(
new MessageHandler.Whole<String>() {
public void onMessage(String name) {
try {
session.getBasicRemote().sendText(“Hello “ + name);
} catch (IOException ioe) {
// Handle failure.
}
}
});
}
}

18

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Hello World Client
public class HelloClient extends Endpoint {
@Override
public void onOpen(Session session,
EndpointConfig configuration) {
try {
session.getBasicRemote().sendText("Hello you!");
} catch (IOException ioe) {
. . .
}
}
}

19

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Client Server Configuration
ServerContainer serverContainer =
(ServerContainer) servletContext.getAttribute(
“javax.websocket.server.ServerContainer”);
ServerEndpointConfig serverConfiguration =
ServerEndpointConfig.Builder.create(
HelloServer.class, "/hello").build();
serverContainer.addEndpoint(serverConfiguration);
...
URI clientURI = new URI("ws://myserver.com/websockets/hello");
WebSocketContainer container =
ContainerProvider.getWebSocketContainer();
ClientEndpointConfig clientConfiguration =
ClientEndpointConfig.Builder.create().build();
container.connectToServer(HelloClient.class,
clientConfiguration, clientURI);

20

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Main API Classes: javax.websocket.*
 Endpoint: Intercepts WebSocket lifecycle events
 MessageHandler: Handles all incoming messages for an Endpoint
 RemoteEndpoint: Represents the ‘other end’ of this conversation
 Session: Represents the active conversation

21

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Object Model
Message
Handler

Remote
Endpoint

Message
Handler

Remote
Endpoint

Client

Internet

Session

Message
Handler

Remote
Endpoint

Session

Client

22

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public

WebSocket
Endpoint

Session

Client
Sending the Message
Whole string *

RemoteEndpoint.Basic

sendText(String message)

Binary data *

RemoteEndpoint.Basic

sendBinary(ByteBuffer message)

String fragments

RemoteEndpoint.Basic

sendText(String part, boolean last)

Binary data fragments

RemoteEndpoint.Basic

sendBinary(ByteBuffer part, boolean last)

Blocking stream of text

RemoteEndpoint.Basic

Writer getSendWriter())

Blocking stream of binary
RemoteEndpoint.Basic
data

OutputStream getSendStream()

Custom object

sendObject(Object customObject)

RemoteEndpoint.Basic

* additional flavors: by completion, by future

23

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Receiving the Message
Whole string

MessageHandler.Whole<String>

onMessage(String message)

Binary data

MessageHandler.Whole<ByteBuffer>

onMessage(ByteBuffer message)

String fragments

MessageHandler.Partial<String>

onMessage(String part, boolean last)

Binary data fragments

MessageHandler.Partial<ByteBuffer>

onMessage(ByteBuffer part, boolean last)

Blocking stream of text

MessageHandler.Whole<Reader>

onMessage(Reader r)

Blocking stream of
binary data

MessageHandler.Whole<InputSteam> onMessage(InputStream r)

Custom object of type T

MessageHandler.Whole<T>

24

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public

onMessage(T customObject)
POJO + Annotations

25

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Hello World Annotations
@ServerEndpoint("/hello")
public class HelloBean {
@OnMessage
public String sayHello(String name) {
return “Hello “ + name;
}
}

26

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
WebSocket Annotations
Annotation

Level

Purpose

@ServerEndpoint

class

Turns a POJO into a WebSocket Server Endpoint

@ClientEndpoint

class

Turns a POJO into a WebSocket Client Endpoint

@OnOpen

method

Intercepts WebSocket Open events

@OnClose

method

Intercepts WebSocket Close events

@OnMessage

method

Intercepts WebSocket Message events

method
Flags a matched path segment of a URI-template
parameter

@PathParam
@OnError

27

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

method

Public

Intercepts errors during a conversation
@ServerEndpoint attributes

value

configurator

Custom configuration

decoders

list of message decoder classnames

encoders

list of message encoder classnames

subprotocols

28

Relative URI or URI template
e.g. “/hello” or “/chat/{subscriber-level}”

list of the names of the supported subprotocols

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Custom Payloads
@ServerEndpoint(
value="/hello",
encoders={MyMessage.class},
decoders={MyMessage.class}
)
public class MyEndpoint {
. . .
}

29

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Custom Payloads – Text
public class MyMessage

implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {
private JsonObject jsonObject;
public MyMessage decode(String s) {
jsonObject = new Json.createReader(

new StringReader(s)).readObject();
return this;
}
public boolean willDecode(String string) {
return true; // Only if can process the payload
}
public String encode(MyMessage myMessage) {
return myMessage.jsonObject.toString();
}
}

30

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Custom Payloads – Binary
public class MyMessage
implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> {

public MyMessage decode(ByteBuffer bytes) {
. . .
return this;
}
public boolean willDecode(ByteBuffer bytes) {
. . .
return true; // Only if can process the payload
}
public ByteBuffer encode(MyMessage myMessage) {
. . .
}
}

31

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Chat Sample
@ServerEndpoint("/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@OnOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@OnClose
public void onClose(Session peer) {
peers.remove(peer);
}
...

32

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Chat Sample (Continued)
. . .
@OnMessage
public void message(String message, Session client) {
for (Session peer : peers) {
peer.getRemote().sendObject(message);
}
}
}

33

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
URI Template Matching
@ServerEndpoint(“/orders/{order-id}”)
public class MyEndpoint {
@OnMessage
public void processOrder(
@PathParam(“order-id”) String orderId) {
...
}
}

34

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
@OnMessage Methods
 A parameter type that can be decoded in incoming message
– String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for

which there is a decoder
 An optional Session parameter
 Boolean partial flag
 0..n String parameters annotated with @PathParameter

 A return type that can be encoded in outgoing message
– String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for

which there is an encoder

35

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Java WebSocket Hello World Demo

https://github.com/m-reza-rahman/hello-websocket

36

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Try it Out!

http://download.java.net/glassfish/4.0/release/glassfish-4.0.zip

37

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Resources
 Specification
– JSR: jcp.org/en/jsr/detail?id=356
– Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec

 Reference Implementation
– Tyrus: java.net/projects/tyrus

38

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
39

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 12
40

Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Public
Watch the video with slide synchronization on
InfoQ.com!
http://www.infoq.com/presentations/asynchronous
-event-websocket

Más contenido relacionado

Más de C4Media

Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsC4Media
 
High Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechHigh Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechC4Media
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/awaitC4Media
 
Opportunities and Pitfalls of Event-Driven Utopia
Opportunities and Pitfalls of Event-Driven UtopiaOpportunities and Pitfalls of Event-Driven Utopia
Opportunities and Pitfalls of Event-Driven UtopiaC4Media
 
Datadog: a Real-Time Metrics Database for One Quadrillion Points/Day
Datadog: a Real-Time Metrics Database for One Quadrillion Points/DayDatadog: a Real-Time Metrics Database for One Quadrillion Points/Day
Datadog: a Real-Time Metrics Database for One Quadrillion Points/DayC4Media
 
Are We Really Cloud-Native?
Are We Really Cloud-Native?Are We Really Cloud-Native?
Are We Really Cloud-Native?C4Media
 
CockroachDB: Architecture of a Geo-Distributed SQL Database
CockroachDB: Architecture of a Geo-Distributed SQL DatabaseCockroachDB: Architecture of a Geo-Distributed SQL Database
CockroachDB: Architecture of a Geo-Distributed SQL DatabaseC4Media
 

Más de C4Media (20)

Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery Teams
 
High Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechHigh Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in Adtech
 
Rust's Journey to Async/await
Rust's Journey to Async/awaitRust's Journey to Async/await
Rust's Journey to Async/await
 
Opportunities and Pitfalls of Event-Driven Utopia
Opportunities and Pitfalls of Event-Driven UtopiaOpportunities and Pitfalls of Event-Driven Utopia
Opportunities and Pitfalls of Event-Driven Utopia
 
Datadog: a Real-Time Metrics Database for One Quadrillion Points/Day
Datadog: a Real-Time Metrics Database for One Quadrillion Points/DayDatadog: a Real-Time Metrics Database for One Quadrillion Points/Day
Datadog: a Real-Time Metrics Database for One Quadrillion Points/Day
 
Are We Really Cloud-Native?
Are We Really Cloud-Native?Are We Really Cloud-Native?
Are We Really Cloud-Native?
 
CockroachDB: Architecture of a Geo-Distributed SQL Database
CockroachDB: Architecture of a Geo-Distributed SQL DatabaseCockroachDB: Architecture of a Geo-Distributed SQL Database
CockroachDB: Architecture of a Geo-Distributed SQL Database
 

Último

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 

Último (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 

Building Java HTML5/WebSocket Applications with JSR 356

  • 1. 1 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 2. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /asynchronous-event-websocket InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month
  • 3. Presented at QCon New York www.qconnewyork.com Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide
  • 4. Building Java HTML5/WebSocket Applications with JSR 356 Reza Rahman Java EE/GlassFish Evangelist Reza.Rahman@Oracle.com @reza_rahman
  • 5. Program Agenda  WebSocket Primer  JSR 356: Java API for WebSocket  Demo 3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 6. Interactive Web Sites  HTTP is half-duplex  Flavors of Server Push – Polling – Long Polling – Comet/Ajax  Complex, Inefficient, Wasteful 4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 7. WebSocket to the Rescue  TCP based, bi-directional, full-duplex messaging  Originally proposed as part of HTML5  IETF-defined Protocol: RFC 6455  W3C defined JavaScript API 5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 8. What’s the basic idea ?  Establish connection (Single TCP connection)  Send messages in both direction (Bi-directional)  Send message independent of each other (Full Duplex)  End connection 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 9. Establish a connection Handshake Request Client Server Handshake Response 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 10. Handshake Request GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 11. Handshake Response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat 9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 12. Establishing a Connection Handshake Request Client Server Handshake Response Connected ! 10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 14. WebSocket API www.w3.org/TR/websockets/ 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 15. Java WebSocket Implementations Java-WebSocket Grizzly WebSocket SDK Apache Tomcat 7 Webbit GlassFish Atmosphere Autobahn websockets4j WeberKnecht GNU WebSocket4J Jetty Netty JBoss TorqueBox Caucho Resin SwaggerSocket jWebSocket 13 Kaazing WebSocket Gateway jWamp Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 16. Browser Support 14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 17. JSR 356: Java API for Web Socket  Specification – http://jcp.org/en/jsr/detail?id=356 – http://java.net/projects/websocket-spec – Included in Java EE 7  Reference Implementation – http://java.net/projects/tyrus – Bundled with Glassfish 4 15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 18. Java API for WebSocket Features  Create WebSocket Endpoints – Interface-driven (Endpoint) – Annotation-driven (@ServerEndpoint)  Client and server APIs  SPI for extensions and data frames 16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 19. Basic API Tour 17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 20. Hello World Server public class HelloServer extends Endpoint { @Override public void onOpen(Session session, EndpointConfig configuration) { session.addMessageHandler( new MessageHandler.Whole<String>() { public void onMessage(String name) { try { session.getBasicRemote().sendText(“Hello “ + name); } catch (IOException ioe) { // Handle failure. } } }); } } 18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 21. Hello World Client public class HelloClient extends Endpoint { @Override public void onOpen(Session session, EndpointConfig configuration) { try { session.getBasicRemote().sendText("Hello you!"); } catch (IOException ioe) { . . . } } } 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 22. Client Server Configuration ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute( “javax.websocket.server.ServerContainer”); ServerEndpointConfig serverConfiguration = ServerEndpointConfig.Builder.create( HelloServer.class, "/hello").build(); serverContainer.addEndpoint(serverConfiguration); ... URI clientURI = new URI("ws://myserver.com/websockets/hello"); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientConfiguration = ClientEndpointConfig.Builder.create().build(); container.connectToServer(HelloClient.class, clientConfiguration, clientURI); 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 23. Main API Classes: javax.websocket.*  Endpoint: Intercepts WebSocket lifecycle events  MessageHandler: Handles all incoming messages for an Endpoint  RemoteEndpoint: Represents the ‘other end’ of this conversation  Session: Represents the active conversation 21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 25. Sending the Message Whole string * RemoteEndpoint.Basic sendText(String message) Binary data * RemoteEndpoint.Basic sendBinary(ByteBuffer message) String fragments RemoteEndpoint.Basic sendText(String part, boolean last) Binary data fragments RemoteEndpoint.Basic sendBinary(ByteBuffer part, boolean last) Blocking stream of text RemoteEndpoint.Basic Writer getSendWriter()) Blocking stream of binary RemoteEndpoint.Basic data OutputStream getSendStream() Custom object sendObject(Object customObject) RemoteEndpoint.Basic * additional flavors: by completion, by future 23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 26. Receiving the Message Whole string MessageHandler.Whole<String> onMessage(String message) Binary data MessageHandler.Whole<ByteBuffer> onMessage(ByteBuffer message) String fragments MessageHandler.Partial<String> onMessage(String part, boolean last) Binary data fragments MessageHandler.Partial<ByteBuffer> onMessage(ByteBuffer part, boolean last) Blocking stream of text MessageHandler.Whole<Reader> onMessage(Reader r) Blocking stream of binary data MessageHandler.Whole<InputSteam> onMessage(InputStream r) Custom object of type T MessageHandler.Whole<T> 24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public onMessage(T customObject)
  • 27. POJO + Annotations 25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 28. Hello World Annotations @ServerEndpoint("/hello") public class HelloBean { @OnMessage public String sayHello(String name) { return “Hello “ + name; } } 26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 29. WebSocket Annotations Annotation Level Purpose @ServerEndpoint class Turns a POJO into a WebSocket Server Endpoint @ClientEndpoint class Turns a POJO into a WebSocket Client Endpoint @OnOpen method Intercepts WebSocket Open events @OnClose method Intercepts WebSocket Close events @OnMessage method Intercepts WebSocket Message events method Flags a matched path segment of a URI-template parameter @PathParam @OnError 27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. method Public Intercepts errors during a conversation
  • 30. @ServerEndpoint attributes value configurator Custom configuration decoders list of message decoder classnames encoders list of message encoder classnames subprotocols 28 Relative URI or URI template e.g. “/hello” or “/chat/{subscriber-level}” list of the names of the supported subprotocols Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 31. Custom Payloads @ServerEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class} ) public class MyEndpoint { . . . } 29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 32. Custom Payloads – Text public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject; public MyMessage decode(String s) { jsonObject = new Json.createReader( new StringReader(s)).readObject(); return this; } public boolean willDecode(String string) { return true; // Only if can process the payload } public String encode(MyMessage myMessage) { return myMessage.jsonObject.toString(); } } 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 33. Custom Payloads – Binary public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> { public MyMessage decode(ByteBuffer bytes) { . . . return this; } public boolean willDecode(ByteBuffer bytes) { . . . return true; // Only if can process the payload } public ByteBuffer encode(MyMessage myMessage) { . . . } } 31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 34. Chat Sample @ServerEndpoint("/chat") public class ChatBean { Set<Session> peers = Collections.synchronizedSet(…); @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnClose public void onClose(Session peer) { peers.remove(peer); } ... 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 35. Chat Sample (Continued) . . . @OnMessage public void message(String message, Session client) { for (Session peer : peers) { peer.getRemote().sendObject(message); } } } 33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 36. URI Template Matching @ServerEndpoint(“/orders/{order-id}”) public class MyEndpoint { @OnMessage public void processOrder( @PathParam(“order-id”) String orderId) { ... } } 34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 37. @OnMessage Methods  A parameter type that can be decoded in incoming message – String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for which there is a decoder  An optional Session parameter  Boolean partial flag  0..n String parameters annotated with @PathParameter  A return type that can be encoded in outgoing message – String, primitive, Reader, ByteBuffer, byte[], InputStream, or any type for which there is an encoder 35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 38. Java WebSocket Hello World Demo https://github.com/m-reza-rahman/hello-websocket 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 39. Try it Out! http://download.java.net/glassfish/4.0/release/glassfish-4.0.zip 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 40. Resources  Specification – JSR: jcp.org/en/jsr/detail?id=356 – Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec  Reference Implementation – Tyrus: java.net/projects/tyrus 38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 41. 39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 42. 40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Public
  • 43. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations/asynchronous -event-websocket