Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

Our Talk will be divided into 50% talking and 50% coding :)

And we are going to talk about everything related to WebSockets & its importance to our future web development.

More interesting, we are going to develop an application while we go through the Websocket exploration.

Why

Not HTTP?!

Because we need a bidirectional Interactive Web Sites without much overhead

And less abuse of HTTP to poll the server for updates while sending upstream notifications as distinct HTTP calls.

We need a solution to overcome

Why

So where we can use it ?

This protocol for a variety of web applications:

games, stock tickers, multiuser applications with simultaneous editing, user interfaces exposing server-side services in real time, etc.

Then how it works

Case Study

How it reduces network latency and traffic ??

So where is the problem?

Let's see the following use cases when deploying this simple application to large number of users.

Note: request/response header characters count = 871 byte without the data, and data = 21 byte.

We will compute the network overhead for customers polling for data every 1 second for just HTTP request and response:

Use case A: 1000 client, Network traffic is (871 x 1000)

= 871,000 byte = 6,968,000 bit per second (6.6 Mbps)

Use case B: 10,000 client, Network traffic is (871 x 10,000)

= 8,710,000 byte = 69,680,000 bit per second (66 Mbps)

Use case C: 100,000 client, Network traffic is (871 x 100,000)

= 87,100,000 byte = 696,800,000 bit per second (665 Mbps)

The WebSocket frame is 2 bytes overhead, lets see how it will affect the network traffic in our use cases for message received every 1 second:

Use case A: 1000 client, Network traffic is (2 x 1000)

= 2000 byte = 16,000 bit per second (0.015 Mbps)

Use case B: 10,000 client, Network traffic is (2 x 10000)

= 20,000 byte = 160,000 bit per second (0.153 Mbps)

Use case C: 100,000 client, Network traffic is (2 x 100,000)

= 200,000 byte = 1,600,000 bit per second ( 1.526 Mbps)

By using WebSocket

How it

works??

Simple enough

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

Handshake Response

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Protocol: chat

That's why we

need WebSockets

They are working

Asynchronously.

We need to create an instance of

the WebSocket browser class

This class exposes a bunch of interesting events for which you want to have proper handlers

var wsUri = " ws://echo.websocket.org/";

websocket = new WebSocket(wsUri);

websocket.onopen = function(evt) { onOpen(evt) };

websocket.onmessage = function(evt) { onMessage(evt) };

websocket.onclose = function(evt) { onClose(evt) };

websocket.onerror = function(evt) { onError(evt) };

onopen event is fired when the connection is established.

onmessage event fires whenever the client receives a message from the server.

onclose is triggered when the connection has been closed.

onerror is fired whenever an error occurs.

To send a message to the server, all you need to do is place a call to the method send, as shown here:

var message = "Hello test @" + new Date().toString();

websocket.send(message);

JavaEE 7 WebSocket Support

It is defined under JSR 356: Java API for WebSocket 1.0

Java-WebSocket

WebSocket Gateway

import javax.websocket.*;

@ServerEndpoint("/taman/hello")

public class NotHelloEndpoint

{

@OnMessage

public String greeting(String name)

{

return “welcome peer “ + name;

} }

Annotated

endpoint

WebSocket

Annotations

Other Public API from javax.websocket

programmatic endpoint

can be defined as

public class ChatServer extends Endpoint {

@Override

public void onOpen(Session session, EndpointConfig ec)

{

session.addMessageHandler(...);

}

}

More.....

Level 1 only URI Template Matching

@ServerEndpoint(“/orders/{order-id}”)

public class MyEndpoint {

@OnMessage

public void processOrder(@PathParam(“order-id”) String orderId)

{ . . . }

}

Defining a custom payloads

@serverEndpoint(value="/hello",

encoders={JSONMessage.class},

decoders={JSONMessage.class})

By implementing Encoder/Decoder interface

public class JSONMessage implements Decoder.Text<JSONMessage>,

Encoder.Text<JSONMessage>

{

private JsonObject jsonObj;

public JSONMessage decode(String s)

{

jsonObj = new JsonReader(

new StringReader(s)).readObject();

return this;}

public boolean willDecode(String string) {

return true; // Only if can process the payload }

public String encode(JSONMessage message) {

return message.jsonObject.toString(); }

}

Websocket Client

@ClientEndpoint

public class Client {

@OnMessage

public void message(String message, Session session) {

// process message from server }

}

Tyrus provides us with an easy way to connect to WebSocket endpoint (ContainerProvider:).

We will use it for unit testing

WebSocketContainer container = ContainerProvider.

getWebSocketContainer();

String uri = “ws://localhost:8080/chat/websocket”;

container.connectToServer(ChatClient.class, URI.create(uri));

So lets dirt our hands.

Thanks for listening & being Interested in My session

Yeah, TRUE real time web applications,

no more hacks.

Connected

open

let's explore

the 356 JSR APIs

Disconnected

Time

JSR 356 defines how to write a client/server standards-based WebSocket application.

It defines not just the service endpoint but also ways it can be written with either an annotation-driven (@ServerEndpoint) or an interface-driven (Endpoint) model.

WildFly

jWamp

TorqueBox

Jetty

Grizzly

GNU WebSocket4J

Autobahn

Apache Tomcat 7,8

Netty

WebSocket SDK

WeberKnecht

JBoss

A separate client-side API introduced as well,

Client (@ClientEndpoint)

SwaggerSocket

Caucho Resin

jWebSocket

Atmosphere

GlassFish 4.0

websockets4j

Webbit

Weblogic 12c

Enterprise Architect & Software Development Manager @ efinance, Cairo, Egypt.

WebSocket Support

Provide support in the Java EE platform for

  • Creating WebSocket Java components to handle bi-directional WebSocket conversations.

  • Initiating and intercepting WebSocket events.

  • Creation and consumption of WebSocket text and binary messages.

  • The ability to define WebSocket protocols and content models for an application.

  • Configuration and management of WebSocket sessions, like timeouts, retries, cookies, connection pooling.

  • Specification of how WebSocket application will work within the Java EE security model.

Packaging

  • Client side
  • Classes + resources packaged as a JAR

  • Web Container
  • Only WAR packaging
  • Classes + resources packaged in

WEB-INF/classes or WEB-INF/lib

lets look at simple stock ticker example

How to trace WebSocket messages ?

Request Header

Response

http://about.me/mohamedtaman/

http://www.linkedin.com/in/mohamedtaman

Multi-User Gaming environment

  • HTTP is half-duplex
  • HTTP is verbose
  • Complex, Inefficient, Wasteful
  • Hacks for Server Push
  • Polling
  • Long Polling
  • Comet/Ajax
  • SSE (Server Sent Events)

WebSocket is the solution

  • TCP based, bi-directional, full-duplex messaging.
  • Dramatic reduction in unnecessary network latency and traffic.
  • Most wide adopted HTML5 API by majority of browsers.
  • Supports HTTP proxies, filtering, authentication and intermediaries.
  • Specs:
  • Originally proposed as part of HTML5.
  • IETF-defined Protocol: RFC 6455, Handshake, Data Transfer
  • W3C defined JavaScript API.

Agenda

Explore

HTML5 API

www.w3.org/TR/websockets/

http://caniuse.com/#feat=websockets

How it works On the browser side

one

What does it offer

two

Who implement it?

three

JSR 356 Specification

Not hello world

@ServerEndpoint

Level: class , Turns a POJO into a WebSocket Endpoint

@OnOpen

Level: method ,

Intercepts Open events during clients connection

@ClientEndpoint

Level: class , Turns a POJO to act as a client Endpoint

@OnClose

Level: method, Intercepts close events

@OnError

Level: method ,

Intercepts error during conversation

@PathParam

Level: method parameters ,

Flags a matched path segment of a URI-template

Session

Represents a conversation between two WebSocket

endpoints

Encoders

Interface to convert application objects into WebSocket

messages

Decoders

Interface to convert WebSocket objects into application

messages

Message Handler

Interface to receive incoming messages in a conversation

SPI for extensions and data frames

For compression, multiplexing for example

message

http://tamanmohamed.blogspot.com

close

https://github.com/mohamed-taman

Mohamed Taman @_tamanm

message

error

message

@OnMessage

Level: method , Intercepts message events

{' '}

Time

mohamed.taman@gmail.com

JCP, Java Champions, Was JCP EC, won the 2014 Duke’s choice and 11 annual JCP adopt 2013 awards, Hacker, Speaks Java, Architect, international speaker, IoT Geek, Author.

Learn more about creating dynamic, engaging presentations with Prezi