Using WebSockets in Web apps Presenter: Shahzad Badar.

Slides:



Advertisements
Similar presentations
Games, chat, and finance Toward a truly interactive web with Comet, BAM, and HMTP Emil Ong Chief Evangelist.
Advertisements

Oct, 26 th, 2010 OGF 30, NSI-WG: Network Service Interface working group Web Services Overview Web Services for NSI protocol implementation
Web Services Web Services are the basic fundamental building blocks of invoking features that can be accessed by an application program. The accessibility.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.Public 1 JavaScript/HTML5 Rich Clients Using Java EE 7 Reza Rahman Java EE/GlassFish.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 1.
Rensselaer Polytechnic Institute CSCI-4220 – Network Programming David Goldschmidt, Ph.D.
Martin Kruliš by Martin Kruliš (v1.0)1.
Nikola Dimitroff Creating Genres creatinggenres.com.
6/11/2015Page 1 Web Services-based Distributed System B. Ramamurthy.
Reverse AJAX and HTML5 Based Clients for Embedded Control and Monitoring Systems C Robson, C Bohm, Stockholm University or "HTML5, why should we care?"
Client-server interactions in Mobile Applications.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Android and iOS Development with JAX-RS, WebSocket , and Java EE 7
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 1.
dcDB Stored Procedures: An Overview
1 WebSocket & JSON Java APIs Hackday By Somay David
Lightning Talk Fred Rodriguez Aakash Juneja CPSC 473 March 16, 2012.
WebSockets [intro].
Rensselaer Polytechnic Institute CSCI-4220 – Network Programming David Goldschmidt, Ph.D.
1 Lecture 22 George Koutsogiannakis Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
1 What Can HTML5 WebSocket Do For You? Sidda Eraiah Director of Management Services Kaazing Corporation.
Java Omar Rana University of South Asia. Course Overview JAVA  C/C++ and JAVA Comparison  OOP in JAVA  Exception Handling  Streams  Graphics User.
Copyright, 1996 © Dale Carnegie & Associates, Inc. Presented by Hsiuling Hsieh Christine Liu.
Orbited Scaling Bi-directional web applications A presentation by Michael Carter
1 Cisco Unified Application Environment Developers Conference 2008© 2008 Cisco Systems, Inc. All rights reserved.Cisco Public Introduction to Etch Scott.
1 ObjectRiver Metadata Compilers Programmatic WebSockets JavaOne 2014 – Steven Lemmo.

Zz SOCKET.IO going real time with Arnout Kazemier
Java Servlets and Java Server Pages Norman White Stern School of Business.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
ASP.NET SignalR SoftUni Team Technical Trainers Software University
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Front end (user interfaces) Facilitating the user‘s interaction with the SandS services and processes I. Mlakar, D. Ceric, A. Lipaj Valladolid, 17/12/2014.
REST By: Vishwanath Vineet.
Java Servlets and Java Server Pages
Node.Js 1. 2 Contents About Node.Js Web requirement latest trends Introduction Simple web server creation in Node.Js Dynamic Web pages Dynamic web page.
1 G52IWS: XML Messaging (briefly) Chris Greenhalgh
Computer Network Architecture Lecture 6: OSI Model Layers Examples 1 20/12/2012.
CMS 2: Advanced Web Editing - Content Presented By: Katie Pagano, Special Projects Manager Steve Pont, Product Architect.
Message Framework Topic subscribe for javascript/flex client.
Jetty 9 Dima Ionut Daniel. Contents What is Jetty? History Jetty 9 new features Jetty Configuration Deployment Arhitecture JMX SPDY Handlers WebSocket.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Keith Telle Lead Software Engineer Bit Wizards Behind the Magic: SignalR Demystified.
Developing for Chromecast Cast Companion Library & Custom Receiver Application.
The Java API for XML-Based Web Services. A Web Service example in Java SOAP-awareServlet (e.g. Apache Axis2) SOAP-awareServlet Any class processing the.
Introduction to Node.js® Jitendra Kumar Patel Saturday, January 31, 2015.
Ext JS - Direct Bridging The Gap A DMSBT Presentation By Timothy Chandler.
Ur/Web: A Simple Model for Programming the Web
National College of Science & Information Technology.
Research of Web Real-Time Communication Based on WebSocket
CS5220 Advanced Topics in Web Programming Introduction to WebSocket
Advanced Communication in Web Technologies
Websocket Application
Web Programming Developing Web Applications including Servlets, and Web Services using NetBeans 6.5 with GlassFish.V3.
Java Servlets By: Tejashri Udavant..
Building real-time web apps with WebSockets using IIS, ASP.NET and WCF
WebSocket: Full-Duplex Solution for the Web
WEB API.
Building real-time web apps with HTML5 WebSockets
Introduction to HTML5 and WebSockets.
Web Socket Protocol.
Web Socket Server (using node.js)
Distributed System using Web Services
J2EE Lecture 13: JMS and WebSocket
Distributed System using Web Services
WCF Data Services and Silverlight
Presentation transcript:

Using WebSockets in Web apps Presenter: Shahzad Badar

Agenda Who am I? WebSockets Introduction WebSockets support in Java EE 7

Who am I? A Java evangelist working on java since 2002 Leading Pakistan JUG Working in Primatics Financials

Catch

JEE 7 Theme

Active JSRs JSR 342: Java EE 7 Platform JSR 338: Java API for RESTful Web Services 2.0 JSR 339: Java Persistence API 2.1 JSR 340: Servlet 3.1 JSR 341: Expression Language 3.0 JSR 343: Java Message Service 2.0 JSR 344: JavaServer Faces 2.2 JSR 345: Enteprise JavaBeans 3.2 JSR 346: Contexts and Dependency Injection 1.1 JSR 349: Bean Validation 1.1 JSR 236: Concurrency Utilities for Java EE 1.0 JSR 352: Batch Applications for the Java Platform 1.0 JSR 353: Java API for JSON Processing 1.0 JSR 356: Java API for WebSocket 1.0

Web Socket Support In age of Web 2.0 / 3.0, We need interactive websites but In the standard HTTP model, a server cannot initiate a connection with a client nor send an unrequested HTTP response to a client; thus, the server cannot push asynchronous events to clients.

Why WebSocket? HTTP was good enough for simpler World AJAX – start of bidirectional communication (2005) Today, Web apps demand reliable “real-time” communication with minimal latency Social media apps Financial applications Online games Collaborative Platforms etc …

Why WebSocket? It’s hard to achieve real- time web apps, primarily due to limitations of HTTP HTTP is half duplex ( traffic flows in only one direction at a time) HTTP is verbose HTTP adds latency, latency sucks

HTTP Communication

Simulating full-duplex Tricks Polling Long-polling HTTP Streaming Significant resource consumption overhead Lots of complexity Requesting each n second Maintaining more than one connections

Polling

Long Polling

HTTP Streaming (Comet)

HTTP Request overhead

Network throughput for just the HTTP Use case A: 1,000 clients polling every second: Network throughput is (871 x 1,000) = 871,000 bytes = 6,968,000 bits per second (6.6 Mbps) Use case B: 10,000 clients polling every second: Network throughput is (871 x 10,000) = 8,710,000 bytes = 69,680,000 bits per second (66 Mbps) Use case C: 100,000 clients polling every 1 second: Network throughput is (871 x 100,000) = 87,100,000 bytes = 696,800,000 bits per second (665 Mbps)

WebSocket to rescue TCP based, bi-directional, full-duplex messaging Capable of sending both UTF-8 string and binary frames in any direction at the same time Operating from a single socket across the web As part of HTML5, the application of the client interface will become native to all modern browsers To establish a Web Socket connection, the browser or client simply makes a request to the server for an upgrade from HTTP to a Web Socket

HTML5 Web Sockets! Use case A: 1,000 clients receive 1 message per second: Network throughput is (2 x 1,000) = 2,000 bytes = 16,000 bits per second (0.015 Mbps) [was 6.6 Mbps] Use case B: 10,000 clients receive 1 message per second: Network throughput is (2 x 10,000) = 20,000 bytes = 160,000 bits per second (0.153 Mbps) [was 66 Mbps] Use case C: 100,000 clients receive 1 message per second: Network throughput is (2 x 100,000) = 200,000 bytes = 1,600,000 bits per second (1.526 Mbps) [was 665 Mbps]

Comparison of the unnecessary network throughput overhead

Latency comparison

Web Sockets - Win HTML5 Web Sockets can provide a 500:1 or— depending on the size of the HTTP headers—even a 1000:1 reduction in unnecessary HTTP header traffic 3:1 reduction in latency.

“Reducing kilobytes of data to 2 bytes…and reducing latency from 150ms to 50ms is far more than marginal. In fact, these two factors alone are enough to make Web Sockets seriously interesting to Google.”

Web Sockets The WebSocket specification defines an API establishing "socket" connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time.

Establishing a connection

Handshake Request/Response

Establishing a connection

WebSocket Lifecycle Server Client Connected ! open close message error message Disconnected

Getting Started You open up a WebSocket connection simply by calling the WebSocket constructor: var connection = new WebSocket('ws://localhost:8080/chat', ['soap', 'xmpp']); Notice the ws:. This is the new URL schema for WebSocket connections. There is also wss: for secure WebSocket connection the same way https: is used for secure HTTP connections.

Getting Started // When the connection is open, send some data to the server connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; //close connection connection.close();

Monitoring WebSockets Traffic

WebSockets on Server Javascript: socket.iosocket.io C++: libwebsocketslibwebsockets Errlang: Shirasu.wsShirasu.ws Java: Jetty, GrizllyJetty Node.JS: wsws Ruby: em-websocketem-websocket Python: Tornado, pywebsocketTornadopywebsocket PHP: Ratchet, phpwsRatchetphpws

Browser Support for WebSockets

Java EE 7 – WebSockets Support The Java EE platform includes the Java API for WebSocket (JSR-356), which enables you to create, configure, and deploy WebSocket endpoints in web applications. The WebSocket client API specified in JSR-356 also enables you to access remote WebSocket endpoints from any Java application. The Java API for WebSocket consists of the following packages: The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints. The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.

Creating and Deploying a WebSocket endpoint The process for creating and deploying a WebSocket endpoint is the following: Create an endpoint class. Implement the lifecycle methods of the endpoint. Add your business logic to the endpoint. Deploy the endpoint inside a web application.

Java WebSocket Implementations

Basic API Tour

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

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

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

Sending the Message Whole string *RemoteEndpoint.BasicsendText(String message) Binary data *RemoteEndpoint.BasicsendBinary(ByteBuffer message) String fragmentsRemoteEndpoint.BasicsendText(String part, boolean last) Binary data fragmentsRemoteEndpoint.BasicsendBinary(ByteBuffer part, boolean last) Blocking stream of textRemoteEndpoint.BasicWriter getSendWriter()) Blocking stream of binary data RemoteEndpoint.BasicOutputStream getSendStream() Custom objectRemoteEndpoint.BasicsendObject(Object customObject) * additional flavors: by completion, by future

Receiving the Message Whole stringMessageHandler.Whole onMessage(String message) Binary dataMessageHandler.Whole onMessage(ByteBuffer message) String fragmentsMessageHandler.Partial onMessage(String part, boolean last) Binary data fragmentsMessageHandler.Partial onMessage(ByteBuffer part, boolean last) Blocking stream of textMessageHandler.Whole onMessage(Reader r) Blocking stream of binary data MessageHandler.Whole onMessage(InputStream r) Custom object of type TMessageHandler.Whole onMessage(T customObject)

POJO + Annotations

Hello World public class HelloBean public String sayHello(String name) { return “Hello “ + name; } }

WebSocket Annotations classTurns a POJO into a WebSocket Server classTurns a POJO into a WebSocket Client methodIntercepts WebSocket Open methodIntercepts WebSocket Close methodIntercepts WebSocket Message method parameter Flags a matched path segment of a methodIntercepts errors during a conversation

@ServerEndpoint attributes value Relative 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

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

Custom Payloads – Text public class MyMessage implements Decoder.Text, Encoder.Text { 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(); } }

Custom Payloads – Binary public class MyMessage implements Decoder.Binary, Encoder.Binary { 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) {... } }

Chat public class ChatBean { Set peers = public void onOpen(Session peer) { peers.add(peer); public void onClose(Session peer) { peers.remove(peer); }...

Chat Sample public void message(String message, Session client) { for (Session peer : peers) { peer.getBasicRemote().sendObject(message); } } }

URI Template public class MyEndpoint public void String orderId) {... } }

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

Demo

References html html