introduction to the java api for websocket (jsr 356)

33
Introduction to the Java API for WebSocket (JSR 356) Reza Rahman Java EE/GlassFish Evangelist [email protected] @reza_rahman

Upload: reza-rahman

Post on 08-May-2015

39.671 views

Category:

Technology


4 download

DESCRIPTION

This session examines the efforts with JSR 356 to support WebSocket in the Java programming model, from its base-level integration in the Java Servlet and Java EE 7 containers to a new, easy-to-use API and tool set that is part of the standard enterprise Java platform. The family of HTML5 technologies has pushed the pendulum away from thin client technologies and toward ever-more-capable Web clients running on today’s browsers. In particular, WebSocket brings new opportunities for efficient peer-to-peer communication, providing the basis for a new generation of interactive and “live” Web applications. JSR 356 brings these capabilities to server-side Java developers. The session is a deep dive into JSR 356 including some demos.

TRANSCRIPT

Page 1: Introduction to the Java API for WebSocket (JSR 356)

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

Introduction to the Java API for WebSocket (JSR 356)Reza RahmanJava EE/GlassFish [email protected]@reza_rahman

Page 2: Introduction to the Java API for WebSocket (JSR 356)

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

Agenda

WebSocket 101

JSR 356: Java API for WebSocket

Demo

Page 3: Introduction to the Java API for WebSocket (JSR 356)

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

WebSocket

HTTP/TCP based, bi-directional, full-duplex messaging Originally proposed as part of HTML5 IETF-defined Protocol: RFC 6455 W3C defined JavaScript API

Page 4: Introduction to the Java API for WebSocket (JSR 356)

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

Establish a connection

Client

Handshake Request

Handshake Response

Server

Page 5: Introduction to the Java API for WebSocket (JSR 356)

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

Handshake Request

GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13

Page 6: Introduction to the Java API for WebSocket (JSR 356)

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

Handshake Response

HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Protocol: chat

Page 7: Introduction to the Java API for WebSocket (JSR 356)

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

Establishing a Connection

ServerClient

Handshake Request

Handshake Response

Connected !

Page 8: Introduction to the Java API for WebSocket (JSR 356)

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

WebSocket Lifecycle

ServerClient

Connected !

open open

close

message

message

error

messagemessage

Disconnected

Page 9: Introduction to the Java API for WebSocket (JSR 356)

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

Browser Support

Page 10: Introduction to the Java API for WebSocket (JSR 356)

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

Java API for WebSocket

Create WebSocket Endpoints– Interface-driven (Endpoint)

– Annotation-driven (@ServerEndpoint)

Client and server APIs Part of Java EE 7 SPI for extensions and data frames

Page 11: Introduction to the Java API for WebSocket (JSR 356)

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

Basic API Tour

Page 12: Introduction to the Java API for WebSocket (JSR 356)

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

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. } } }); }}

Page 13: Introduction to the Java API for WebSocket (JSR 356)

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

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) { ... } }}

Page 14: Introduction to the Java API for WebSocket (JSR 356)

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

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);

Page 15: Introduction to the Java API for WebSocket (JSR 356)

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

Sending the Message

Whole string *RemoteEndpoint.Basic

sendText(String message)

Binary data *RemoteEndpoint.Basic

sendBinary(ByteBuffer message)

String fragmentsRemoteEndpoint.Basic

sendText(String part, boolean last)

Binary data fragmentsRemoteEndpoint.Basic

sendBinary(ByteBuffer part, boolean last)

Blocking stream of text

RemoteEndpoint.Basic

Writer getSendWriter())

Blocking stream of binary data

RemoteEndpoint.Basic

OutputStream getSendStream()

Custom objectRemoteEndpoint.Basic

sendObject(Object customObject)

* Additional flavors: by completion, by future

Page 16: Introduction to the Java API for WebSocket (JSR 356)

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

Receiving the Message

Whole stringMessageHandler.Whole<String>

onMessage(String message)

Binary dataMessageHandler.Whole<ByteBuffer>

onMessage(ByteBuffer message)

String fragmentsMessageHandler.Partial<String>

onMessage(String part, boolean last)

Binary data fragments

MessageHandler.Partial<ByteBuffer>

onMessage(ByteBuffer part, boolean last)

Blocking streamof text

MessageHandler.Whole<Reader>

onMessage(Reader r)

Blocking streamof binary data

MessageHandler.Whole<InputSteam>

onMessage(InputStream r)

Custom objectof type T

MessageHandler.Whole<T>

onMessage(T customObject)

Page 17: Introduction to the Java API for WebSocket (JSR 356)

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

POJO + Annotations

Page 18: Introduction to the Java API for WebSocket (JSR 356)

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

Hello World Annotations

@ServerEndpoint("/hello")public class HelloBean {

@OnMessage public String sayHello(String name) { return "Hello " + name; }}

Page 19: Introduction to the Java API for WebSocket (JSR 356)

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

WebSocket Annotations

Annotation Level Purpose

@ServerEndpoint ClassTurns a POJO into a WebSocket Server Endpoint

@ClientEndpoint ClassTurns 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

@PathParamMethod

ParameterFlags a matched path segment of a URI-template

@OnError Method Intercepts errors during a conversation

Page 20: Introduction to the Java API for WebSocket (JSR 356)

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

@ServerEndpoint Attributes

valueRelative URI or URI template

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

configurator Custom configuration

decoders List of message decoder classnames

encoders List of message encoder classnames

subprotocols List of the names of the supported subprotocols

Page 21: Introduction to the Java API for WebSocket (JSR 356)

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

Custom Payloads

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

Page 22: Introduction to the Java API for WebSocket (JSR 356)

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

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(); }}

Page 23: Introduction to the Java API for WebSocket (JSR 356)

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

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) { ... }}

Page 24: Introduction to the Java API for WebSocket (JSR 356)

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

Chat Sample

@Singleton @ServerEndpoint("/chat")

public class ChatServer {

private Set<Session> peers = new HashSet();

@OnOpen public void onOpen(Session peer) { peers.add(peer); }

@OnClose public void onClose(Session peer) { peers.remove(peer); } ...

Page 25: Introduction to the Java API for WebSocket (JSR 356)

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

Chat Sample (Continued)

...

@OnMessage

public void message(String message) {

for (Session peer : peers) { peer.getBasicRemote().sendText(message); } }}

Page 26: Introduction to the Java API for WebSocket (JSR 356)

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

URI Template Matching

@ServerEndpoint("/orders/{order-id}")public class MyEndpoint { @OnMessage public void processOrder( @PathParam("order-id") String orderId) { ... }}

Page 27: Introduction to the Java API for WebSocket (JSR 356)

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

@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

Page 28: Introduction to the Java API for WebSocket (JSR 356)

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

Java WebSocket Demo

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

https://github.com/m-reza-rahman/whiteboard

Page 29: Introduction to the Java API for WebSocket (JSR 356)

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

Try it Out!

http://dlc.sun.com.edgesuite.net/glassfish/4.0.1/promoted/

Page 30: Introduction to the Java API for WebSocket (JSR 356)

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

Java WebSocket Implementations

Tomcat

GlassFish

TomEE

Page 31: Introduction to the Java API for WebSocket (JSR 356)

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

Summary

Bi-directional full-duplex communication on the web– Chat, online multiplayer games, collaboration, real time monitoring

Java API for WebSocket standardized as part of Java EE 7– Interface-driven– Annotation-driven

Client and server APIs Supported by major server-side Java platforms

Page 32: Introduction to the Java API for WebSocket (JSR 356)

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

Learning More

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

– GlassFish: http://glassfish.org

Dig Deeper– Java EE Tutorial:

http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm

– Java EE 7 Hands-on-Lab: https://glassfish.java.net/hol/

– Cargo Tracker Java EE Blue Prints Project: https://java.net/projects/cargotracker/

Page 33: Introduction to the Java API for WebSocket (JSR 356)

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