Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Yeah, TRUE real time web applications, no more hacks (a hack session)

No description
by

Mohamed Taman

on 16 April 2016

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Yeah, TRUE real time web applications, no more hacks (a hack session)

{' '}
How it
works??
JavaEE 7 WebSocket Support
It is defined under JSR 356:
Java API for WebSocket 1.0
Explore
HTML5 API

Why
Not HTTP?!

Because we need a
bidirectional
Interactive Web Sites without much
overhead
Case Study
How it reduces network latency and traffic ??
Agenda
And we are going to talk about everything related to
WebSockets
& its importance to our future web development.
Yeah,
TRUE
real time web applications,
no more hacks.

Mohamed Taman
@_tamanm

Enterprise Architect & Software Development Manager @ efinance, Cairo, Egypt.
http://tamanmohamed.blogspot.com
http://www.linkedin.com/in/mohamedtaman
https://github.com/mohamed-taman
mohamed.taman@gmail.com
http://about.me/mohamedtaman/
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.
More
interesting
, we are going to develop an application while we go through the
Websocket
exploration.
Our Talk will be divided into
50%
talking and
50%
coding
:)
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
HTTP is
half-duplex
HTTP is
verbose
Hacks for Server Push
Polling
Long Polling
Comet/Ajax
SSE (Server Sent Events)
Complex, Inefficient, Wasteful
Multi-User Gaming environment
WebSocket is the solution
Why
TCP
based,
bi-directional
,
full-duplex
messaging
.
Dramatic reduction in unnecessary network
latency
and
traffic
.
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
.
Most wide adopted
HTML5
API by majority of browsers.
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
lets look at simple stock ticker example
Request Header
Response
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
)
By using WebSocket
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 C:
100,000 client, Network traffic is (2 x 100,000)
= 200,000 byte = 1,600,000 bit per second (
1.526 Mbps
)
Use case B:
10,000 client, Network traffic is (2 x 10000)
= 20,000 byte = 160,000 bit per second (
0.153 Mbps
)
www.w3.org/TR/websockets/
http://caniuse.com/#feat=websockets
They are working
Asynchronously
.
How it works On the browser side
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
.
onclose
is triggered when the
connection has been closed
.
onmessage
event fires whenever the client receives a
message from the server.
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
);
Time
Simple enough
Handshake Request
Handshake Response
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
HTTP/1.1 101
Switching Protocols
Upgrade:
websocket
Connection:
Upgrade
Sec-WebSocket-Accept:
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-
WebSocket-Protocol:
chat
open
message
open
message
message
close
Connected
error
message
message
message
Disconnected
That's why we
need WebSockets
three
two
one
What does it offer
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.
A separate client-side API introduced as well,
Client (
@ClientEndpoint
)
WebSocket Support
Who implement it?
Java-WebSocket
Grizzly
Apache Tomcat 7,8
GlassFish 4.0
Autobahn
WeberKnecht
Jetty
JBoss
Caucho Resin
jWebSocket
WebSocket Gateway
WebSocket SDK
Webbit
Atmosphere
websockets4j
GNU WebSocket4J
Netty
TorqueBox
SwaggerSocket
jWamp
JSR 356 Specification
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.
Weblogic 12c
WildFly
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
How to trace
WebSocket
messages ?
let's explore
the 356 JSR APIs
import javax.websocket.*;

@ServerEndpoint
("/taman/hello")
public

class

NotHelloEndpoint
{

@OnMessage



public

String greeting(String name)
{

return


welcome peer


+ name;
} }
Not hello world
WebSocket
Annotations
@ServerEndpoint
@ClientEndpoint
@OnMessage
@PathParam
@OnOpen
@OnClose
@OnError
Level:
class , Turns a POJO into a WebSocket Endpoint
Level:
method, Intercepts close events
Level:
method , Intercepts message events
Level:
class , Turns a POJO to act as a client Endpoint
Level:
method ,
Intercepts error during conversation
Level:
method ,
Intercepts Open events during clients connection
Level:
method parameters ,
Flags a matched path segment of a URI-template
Level 1 only URI Template Matching
SPI for extensions and data frames
Defining a custom payloads
For compression, multiplexing for example
More.....
By implementing
Encoder/Decoder
interface
@serverEndpoint
(value="/hello",
encoders=
{JSONMessage.class}
,

decoders=
{JSONMessage.class}
)
@ServerEndpoint
(“/orders/
{order-id}
”)
public

class
MyEndpoint {

@OnMessage


public

void
processOrder(
@PathParam(
“order-id”
)

String orderId)
{ . . . }
}
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
}
}
Annotated
endpoint
Other Public API from
javax.websocket
Session
Encoders
Message Handler
Decoders
Represents a conversation between two WebSocket
endpoints
Interface to convert WebSocket objects into application
messages
Interface to receive incoming messages in a conversation
Interface to convert application objects into WebSocket
messages
programmatic endpoint
can be defined as
public

class
ChatServer extends
Endpoint
{
@Override
public

void
onOpen(
Session
session,
EndpointConfig
ec)
{
session.addMessageHandler(...);
}
}
Tyrus
provides us with an easy way to connect to WebSocket endpoint (
ContainerProvider
:).
We will use it for unit testing
So lets dirt our hands.
WebSocketContainer container = ContainerProvider.
getWebSocketContainer();

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

container.connectToServer(ChatClient.class, URI.create(uri));
Time
Thanks for
listening
& being
Interested
in My session
Full transcript