websockets - realtime em mundo conectado

Download WebSockets - Realtime em Mundo Conectado

If you can't read please download the document

Upload: bruno-borges

Post on 24-May-2015

220 views

Category:

Technology


4 download

DESCRIPTION

Como usar WebSockets, Java EE 7, WebLogic 12.1.3

TRANSCRIPT

  • 1. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSockets: Realtime Em Um Mundo ConectadoBruno BorgesPrincipal Product ManagerOracle Latin AmericaAgosto, 2014

2. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |SpeakerBruno BorgesPrincipal Product Manager, Java EvangelistOracle Latin [email protected]@oracle.com 3. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket Overview 4. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket OverviewThe WebSocket API in HTML5Enables use of WebSocket in HTML5/web applicationsOpen/Close connectionsSend/Receive messagesFully asynchronousEvent driven, listen and respond to events 5. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket OverviewBrowser Support for WebSocket APIBroad base of support for WebSocket in modern browsersFirefox 28+, Chrome 33+, Safari 7+, IE 10+Including mobile browsershttp://caniuse.com/#search=websocket 6. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket OverviewCommon Use CasesTime critical data deliveryStocking monitoring, tradingTicket reservation, seat selectionApplications that require true bi-directional exchanges with low latencyIoT control systems, gaming, gamblingHigh levels of interactivityChat systems, online sales engagement tools, support systems for trouble shootingHigh throughput applications 7. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |The WebSocket Protocol (RFC 6455)Protocol OverviewDefines handshake and data transferIntroduces new URI schemesws-URI = ws: // host [:port] path [ ? query ]wss-URI = wss: // host [:port] path [ ? query ]# MUST be escaped as %23 (URI fragments are meaningless)Imposes an Origin Security ModelSupports extensibilityTunnel other protocol by supporting sub-protocols, extend protocol features by supporting extensions 8. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |The WebSocket ProtocolOpening HandshakeWebLogic Server 12.1.3HTTP 9. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |The WebSocket ProtocolProtocol UpgradeWebLogic Server 12.1.3WebSocket 10. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |The WebSocket ProtocolKeep Alive: Ping and PongPing FramePong FramePing FramePong FrameWebLogic Server 12.1.3 11. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |The WebSocket ProtocolClosing HandshakeWebLogic Server 12.1.3Close FrameData FrameData FrameData FrameClose Frame 12. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Developing WebSocket Applications using the Java Standard 13. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0The Java Standard for WebSocket ApplicationsJava community proposed and developed a specification and standard API for using WebSocket with the Java platformMany companies and individuals representedOracle specification lead, developer of reference implementation with Project TyrusJSR-356Specification finalized and approved May 2013Included in Java EE 7 specificationIntegrated into WebLogic Server 12.1.3 14. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Core ConceptsEndpointA websocket endpoint is a Java component that represents one side of a sequence of websocket interactions between two connected peersConnectionA websocket connection is the networking connection between the two endpoints which are interacting using the websocket protocolPeerA websocket peer is used to represent the another participant of the websocket interactions with the endpointSessionA websocket session is used to represent a sequence of websocket interactions between an endpoint and a single peerClient Endpoints and Server EndpointsA client endpoint is an endpoint that initiates a connection to a peer but does not accept new onesA server endpoint is an endpoint that accepts websocket connections from peers but does not initiate connections to peers. 15. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Creating a WebSocket requires a Java class that acts as an EndpointParticipate in lifecycle: establish connections with peers, handle errors, close connectionsSend and receive messagesEndpoints can be created from:Annotation based approach using WebSocket Annotations, @ServerEndpointProgrammatic API where Java class extends WebSocket API classEndpoints can be defined as:Clients which connect to one server only at a timeServers which many clients can connect to at any time 16. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Annotated ServerEndpoint Exampleimport javax.websocket.OnMessage;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/echo")public class EchoServer {@OnMessagepublic String echo(String incomingMessage) {return String.format("I got this (%s) message so I am sending it back!, incomingMessage);}} 17. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Annotated ServerEndpoint Example@ServerEndpoint("/echo")public class EchoServer {@OnMessagepublic void onMessage(Session session, String message) {session.getOpenSessions() .forEach(s -> s.getBasicRemote().sendText(message));}} 18. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Annotated Path Parameter Example@ServerEndpoint("/users/{username}")public class UserEndpoint {@OnMessagepublic String handle(String message, @PathParam("username") String user) {return message + message + from user + user;}} 19. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Programmatic Endpoint Examplepublic class ProgrammaticEchoServer extends Endpoint {@Overridepublic void onOpen(final Session session, EndpointConfig endpointConfig) {mySession.addMessageHandler(new MessageHandler.Whole() {public void onMessage(String text) {try {mySession.getBasicRemote() .sendText(I got this ( + text + ) + so I am sending it back !);} catch (IOException ioe) { }}});}} 20. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Annotated ClientEndpoint Exampleimport java.io.IOException;import javax.websocket.*;@ClientEndpointpublic class HelloClient {@OnOpenpublic void init(Session session) {try {session.getBasicRemote().sendText("Hello you !");} catch (IOException ioe) {// error}}} 21. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Programmatic ClientEndpoint Examplepublic class HelloClient extends Endpoint {@Overridepublic void onOpen(Session session, EndpointConfig EndpointConfig) {try {session.getBasicRemote().sendText("Hello you !");} catch (IOException e) {// error}} 22. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Responding to Lifecycle EventsAnnotationProgrammatic APIOpen Event@OnOpenpublic void onOpen(Session session, EndpointConfig config)Message Event@OnMessageCreate instance of relevant javax.websocket.MessageHandlerRegister with SessionError Event@OnErrorpublic void onError(Session session, Throwable throwable)Close Event@OnClosepublic void onClose(Session session, CloseReason reason) 23. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Receiving Message from PeersAnnotate a suitable method with @OnMessageImplement an appropriate MessageHandler interfaceAdd it to the Session@OnMessageVoid handleText(String message)@OnMessagepublic void handlePartialText( String message, boolean isLast)SimpleHandler implements MessageHandler.Whole { ... }session.addMessageHandler(new SimpleHandler()); 24. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Receiving Message from Peer with @OnMessageMessage TypeAnnotated Method FormTextpublic void handleText(String message)public void handleReader(Reader r)public void handleTextPieces(String message, boolean isLast)Binarypublic void handleBinary(ByteBuffer bytebuf)public void handleStream(InputStream is)public void handleBinaryPieces(ByteBuffer bytebuf, boolean isLast)Any Objectpublic void handleObject(CustomObject co) 25. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Receiving Message Programmatically from PeersMessage TypeMessage Handler InterfaceTextMessageHandler.WholeMessageHandler.WholeMessageHandler.PartialBinaryMessageHandler.WholeMessageHandler.PartialMessageHandler.WholeAny ObjectMessageHandler.Whole 26. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Sending Messages to PeersReturn a value from the @OnMessage methodAccess the RemoteEndpoint interface from the Session objectCall the relevant send method@OnMessage public String echoToUppercase(String msg) { return msg.toUpperCase(); }RemoteEndpoint remote = session.getBasicRemote();remote.sendText(This is a txt message); 27. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Asynchronous and Synchronous Sending ModesModeUsageInterface and MethodSynchronousMost commonly use modeSend methods block until transmission of message is completeRemoteEndpoint.Basicvoid sendText(String message)AsynchronousSend methods return immediately before transmissionFuture and Callback options for completion handlingRemoteEndpoint.AsyncFuture sendText(String message)void sendText(String message, SendHandler handler) 28. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Example Encoderpublic class AuctionMessageEncoder implements Encoder.Text {@Overridepublic String encode(AuctionMessage object) throws EncodeException {JsonObject json = null;switch (object.getType()) {case AuctionMessage.AUCTION_TIME_RESPONSE:json = Json.createObjectBuilder().add("type", object.getType()).add("communicationId", object.getCommunicationId()).add("data", (int) object.getData()).build();break;}return json.toString();} 29. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Example Decoderpublic class AuctionMessageDecoder implements Decoder.Text {@Overridepublic AuctionMessage decode(String s) {JsonReader jsonReader = Json.createReader(new StringReader(s));JsonObject json = jsonReader.readObject();return new AuctionMessage(json.getString("type"),json.getString("communicationId"), json.getString("data"));}@Overridepublic boolean willDecode(String s) {return s.contains(AuctionMessage.BID_REQUEST)|| s.contains(AuctionMessage.AUCTION_LIST_REQUEST)|| s.contains(AuctionMessage.LOGIN_REQUEST));} 30. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Configuring Encoders and DecodersAnnotationSpecify encoder and decoder values on @ServerEndpointProgrammaticAdd encoder/decoder classes to ServerEndpointConfig object@ServerEndpoint( decoders = { AuctionMessageDecoder.class }, encoders = { AuctionMessageEncoder.class })List encoders = new List();encoders.add(AuctionMessageEncoder.class);encoders.add(AuctionMessageDecoder.class);ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AuctionEndpoint.class, "/bids).encoders(encoders).build(); 31. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |Securing WebSocket Applications 32. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0SecurityBased on the Servlet modelWebSocket Endpoints are considered resources via their uriSo one canRequire users be authenticated to access a WebSocket endpointLimit access to a WebSocket endpointto certain users, via role mappingto an encrypted protocol (wss://) 33. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |JSR-356: Java API for WebSocket 1.0Example secured configuration in web.xmlSecure Customer WebSocket Endpoint/customer/feedGETCUSTOMERSCONFIDENTIALBASICCUSTOMERS 34. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |Tyrus Reference ImplementationOfficial Pagehttp://tyrus.java.netUser Guide (1.8)https://tyrus.java.net/documentation/1.8/user-guide.htmlUsed byGlassFish 4.0+WebLogic 12c (12.1.3+) 35. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |Java EE 7 WebSocket API in WebLogic 12.1.3 36. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebLogic Server 12.1.3 Mobile, Developer ProductivityWLS 12.1.3ClientsHTML5 clientsADF MobileProxiesOTDApacheOHSWeb Sockets (JSR 356)TopLink Data ServicesServer-Sent EventsJAX-RS 2.0WebSocket EmulationWebSocket EmulationJAX-RS 2.0, WebSocket 1.0 JSON Programming API JPA 2.1Server-Sent EventsWebSocket EmulationJPA-RSJPAChange NotificationDatabaseJSON Programming APIHTTP/S, JSON/XMLWebSocket, Server-Sent Events, Long pollingJava EE 7APIsAdditional WebLogic Value-AddOracle Confidential Internal/Restricted/Highly Restricted37 37. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket Protocol FallbackEnabling WebSocket Use Across All Environments 38. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |Happy HTML5 WebSocketsHTML5 and the Java API for WebSocketEnables lots of new opportunities for developing highly interactive applications and rich user experiencesLightweight, fast, easy to programStandardizing across the industryBut ...WebSockets are not universally supported across all current environmentsMost browsers support HTML5 and WebSockets - but - not all of themFirewalls or proxy servers may block the required frames and protocol 39. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket FallbackProvides a behind-the-scenes fallback mechanism to emulate the WebSocket transport behaviorServer side with an adapter to handle HTTP Long Polling for WebSocket messages when requiredClient side with JavaScript library - orasocket.jsDevelopersUse the Java API for WebSocket to developer your application, enable fallback via web.xml context-paramUse the HTML5 JavaScript WebSocket API on the client, Include OraSocket.js on client pagesSame codebase for native WebSocket Protocol and fallbackTransparent runtime behavior 40. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |Configure Web Applications for WebSockets Fallback SupportImport orasocket.js in HTMLModify web.xmlEnable fallback mechanismcom.oracle.tyrus.fallback.enabledtrue 41. Copyright 2014, Oracle and/or its affiliates. All rights reserved. |WebSocket Connections with FallbackComposedFramedSent// JS Client ws = new WebSocket(ws:// + uri); ws.onmessage = function (evt) { }; ws.open = function(evt) { ... } ws.onerror = function (evt) { ... }Dispatcher