SlideShare a Scribd company logo
1 of 58
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 me
@shahzadbadar
shahzadbadar@gmail.com
http://www.implementsjava.com
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
Connected !

open

open

message

Client

message

error
message

Server
message

close

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.io
 C++: libwebsockets
 Errlang: Shirasu.ws
 Java: Jetty, Grizlly

 Node.JS: ws
 Ruby: em-websocket
 Python: Tornado, pywebsocket

 PHP: Ratchet, phpws
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 {
@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.
}
}
});
}
}
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) {
. . .
}
}
}
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.Basic

sendText(String message)

Binary data *

RemoteEndpoint.Basic

sendBinary(ByteBuffer message)

String fragments

RemoteEndpoint.Basic

sendText(String part, boolean last)

Binary data fragments

RemoteEndpoint.Basic

sendBinary(ByteBuffer part, boolean last)

Blocking stream of text

RemoteEndpoint.Basic

Writer getSendWriter())

Blocking stream of binary
RemoteEndpoint.Basic
data

OutputStream getSendStream()

Custom object

sendObject(Object customObject)

RemoteEndpoint.Basic

* additional flavors: by completion, by future
Receiving the Message
Whole string

MessageHandler.Whole<String>

onMessage(String message)

Binary data

MessageHandler.Whole<ByteBuffer>

onMessage(ByteBuffer message)

String fragments

MessageHandler.Partial<String>

onMessage(String part, boolean last)

Binary data fragments

MessageHandler.Partial<ByteBuffer>

onMessage(ByteBuffer part, boolean last)

Blocking stream of text

MessageHandler.Whole<Reader>

onMessage(Reader r)

Blocking stream of
binary data

MessageHandler.Whole<InputSteam> onMessage(InputStream r)

Custom object of type T

MessageHandler.Whole<T>

onMessage(T customObject)
POJO + Annotations
Hello World Annotations
@ServerEndpoint("/hello")
public class HelloBean {

@OnMessage
public String sayHello(String name) {
return “Hello “ + name;
}
}
WebSocket Annotations
Annotation

Level

Purpose

@ServerEndpoint

class

Turns a POJO into a WebSocket Server Endpoint

@ClientEndpoint

class

Turns 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

@PathParam
@OnError

method
Flags a matched path segment of a URI-template
parameter
method

Intercepts 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 Payloads
@ServerEndpoint(
value="/hello",
encoders={MyMessage.class},
decoders={MyMessage.class}
)
public class MyEndpoint {
. . .
}
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();
}
}
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) {
. . .
}
}
Chat Sample
@ServerEndpoint("/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@OnOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@OnClose
public void onClose(Session peer) {
peers.remove(peer);
}
...
Chat Sample (Continued)
. . .
@OnMessage
public void message(String message, Session client) {
for (Session peer : peers) {
peer.getBasicRemote().sendObject(message);
}
}
}
URI Template Matching
@ServerEndpoint(“/orders/{order-id}”)
public class MyEndpoint {
@OnMessage
public void processOrder(
@PathParam(“order-id”) 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 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
Demo
References
 http://www.websocket.org/quantum.html
 http://blog.arungupta.me
 https://developer.mozilla.org/en/docs/WebSockets
 http://www.w3.org/TR/html5/

 http://www.rahmannet.net/
 http://www.oracle.com/technetwork/articles/java/jsr35

6-1937161.html
WebSockets in JEE 7

More Related Content

What's hot

Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with javaJeongHun Byeon
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Ericom Software
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsArun Gupta
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets PresentationVolodymyr Lavrynovych
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaArun Gupta
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSocketsGunnar Hillert
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민JavaCommunity.Org
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket IntroductionMarcelo Jabali
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Arun Gupta
 
Building Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsBuilding Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsSergi Almar i Graupera
 
Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!jfarcand
 
ServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIGert Vanthienen
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkFabio Tiriticco
 
WebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptWebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptMichele Di Salvatore
 
Comet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumComet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumJoe Walker
 

What's hot (20)

Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
Websockets and SockJS, Real time chatting
Websockets and SockJS, Real time chattingWebsockets and SockJS, Real time chatting
Websockets and SockJS, Real time chatting
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Intro to WebSockets
Intro to WebSocketsIntro to WebSockets
Intro to WebSockets
 
Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 
vlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentationvlavrynovych - WebSockets Presentation
vlavrynovych - WebSockets Presentation
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
 
Jetty Continuation - 이상민
Jetty Continuation - 이상민Jetty Continuation - 이상민
Jetty Continuation - 이상민
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket Introduction
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
Jetty TLS troubleshooting
Jetty TLS troubleshootingJetty TLS troubleshooting
Jetty TLS troubleshooting
 
Building Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsBuilding Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSockets
 
Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!
 
ServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBIServiceMix 4 -- Integrating OSGi with JBI
ServiceMix 4 -- Integrating OSGi with JBI
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
WebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptWebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascript
 
Comet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumComet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way Medium
 

Similar to WebSockets in JEE 7

Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"Sachin Katariya
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketMauricio "Maltron" Leal
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersViktor Gamov
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax Wrajivmordani
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebPeter Lubbers
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...PROIDEA
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01purans
 
Jax ws
Jax wsJax ws
Jax wsF K
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservicelonegunman
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersoazabir
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 

Similar to WebSockets in JEE 7 (20)

Building real-time-collaborative-web-applications
Building real-time-collaborative-web-applicationsBuilding real-time-collaborative-web-applications
Building real-time-collaborative-web-applications
 
Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"Webinar slides "Building Real-Time Collaborative Web Applications"
Webinar slides "Building Real-Time Collaborative Web Applications"
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Websocket
WebsocketWebsocket
Websocket
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax W
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the Web
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
 
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerryjWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
 
Jax ws
Jax wsJax ws
Jax ws
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Real-time ASP.NET with SignalR
Real-time ASP.NET with SignalRReal-time ASP.NET with SignalR
Real-time ASP.NET with SignalR
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

WebSockets in JEE 7

  • 1. Using WebSockets in Web apps Presenter: Shahzad Badar
  • 2. Agenda  Who am I?  WebSockets Introduction  WebSockets support in Java EE 7
  • 3. Who am I?  A Java evangelist working on java since 2002  Leading Pakistan JUG  Working in Primatics Financials
  • 5.
  • 6.
  • 8.
  • 9. 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
  • 10. 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.
  • 11. 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 …
  • 12. 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
  • 14. 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
  • 19. 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)
  • 20. 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
  • 21. 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]
  • 22. Comparison of the unnecessary network throughput overhead
  • 24. 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.
  • 25. “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.”
  • 26. 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.
  • 31. 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.
  • 32. 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();
  • 34. WebSockets on Server  Javascript: socket.io  C++: libwebsockets  Errlang: Shirasu.ws  Java: Jetty, Grizlly  Node.JS: ws  Ruby: em-websocket  Python: Tornado, pywebsocket  PHP: Ratchet, phpws
  • 35. Browser Support for WebSockets
  • 36. 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.
  • 37. 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.
  • 40. 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. } } }); } }
  • 41. 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) { . . . } } }
  • 42. 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);
  • 43. Sending the Message Whole string * RemoteEndpoint.Basic sendText(String message) Binary data * RemoteEndpoint.Basic sendBinary(ByteBuffer message) String fragments RemoteEndpoint.Basic sendText(String part, boolean last) Binary data fragments RemoteEndpoint.Basic sendBinary(ByteBuffer part, boolean last) Blocking stream of text RemoteEndpoint.Basic Writer getSendWriter()) Blocking stream of binary RemoteEndpoint.Basic data OutputStream getSendStream() Custom object sendObject(Object customObject) RemoteEndpoint.Basic * additional flavors: by completion, by future
  • 44. Receiving the Message Whole string MessageHandler.Whole<String> onMessage(String message) Binary data MessageHandler.Whole<ByteBuffer> onMessage(ByteBuffer message) String fragments MessageHandler.Partial<String> onMessage(String part, boolean last) Binary data fragments MessageHandler.Partial<ByteBuffer> onMessage(ByteBuffer part, boolean last) Blocking stream of text MessageHandler.Whole<Reader> onMessage(Reader r) Blocking stream of binary data MessageHandler.Whole<InputSteam> onMessage(InputStream r) Custom object of type T MessageHandler.Whole<T> onMessage(T customObject)
  • 46. Hello World Annotations @ServerEndpoint("/hello") public class HelloBean { @OnMessage public String sayHello(String name) { return “Hello “ + name; } }
  • 47. WebSocket Annotations Annotation Level Purpose @ServerEndpoint class Turns a POJO into a WebSocket Server Endpoint @ClientEndpoint class Turns 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 @PathParam @OnError method Flags a matched path segment of a URI-template parameter method Intercepts errors during a conversation
  • 48. @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
  • 50. 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(); } }
  • 51. 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) { . . . } }
  • 52. Chat Sample @ServerEndpoint("/chat") public class ChatBean { Set<Session> peers = Collections.synchronizedSet(…); @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnClose public void onClose(Session peer) { peers.remove(peer); } ...
  • 53. Chat Sample (Continued) . . . @OnMessage public void message(String message, Session client) { for (Session peer : peers) { peer.getBasicRemote().sendObject(message); } } }
  • 54. URI Template Matching @ServerEndpoint(“/orders/{order-id}”) public class MyEndpoint { @OnMessage public void processOrder( @PathParam(“order-id”) String orderId) { ... } }
  • 55. @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
  • 56. Demo
  • 57. References  http://www.websocket.org/quantum.html  http://blog.arungupta.me  https://developer.mozilla.org/en/docs/WebSockets  http://www.w3.org/TR/html5/  http://www.rahmannet.net/  http://www.oracle.com/technetwork/articles/java/jsr35 6-1937161.html

Editor's Notes

  1. A logical websocket endpoint is represented in the Java WebSocket API as an instance of the Endpoint class. Developers may subclass the Endpoint class in order to intercept lifecycle events of the endpoint: those of a peer connecting, a peer disconnecting and an error being raised during the lifetime of the endpoint. The implementation must use at least one instance of the Endpoint class to represent the logical endpoint. Each instance of the Endpoint class may therefore handle connections to the endpoint from multiple peers. Some implementations may wish to use multiple instances of Endpoint to represent a logical endpoint, perhaps one instance per VM in a distributed server setting. The Java WebSocket API models the sequence of interactions between an endpoint and each of its peers using an instance of the Session class. The interactions between a peer and an endpoint begin with an open notification, followed by some number, possibly zero, of web socket messages between the endpoint and peer, followed by a close notification or error terminal to the connection. For each peer that is interacting with an endpoint, there is one Session instance that represents that interaction. The Session instance corresponding to the peer is passed to the Endpoint instance representing the endpoint at the key events in its lifecycle.
  2. The websocket protocol is a two-way protocol. Once established, the web socket protocol is symmetrical between the two parties in the conversation. The difference between a websocket ‘client’ and a websocket ‘server’ is only in the means by which the two parties are connected. In this specification, we will say that a websocket client is a websocket endpoint that initiates a connection to a peer. We will say that a websocket server is a websocket endpoint that is published an awaits connections from peers. In most deployments, a websocket client will connect to only one websocket server, and a websocket server will accept connections from several clients.
  3. The websocket protocol is a two-way protocol. Once established, the web socket protocol is symmetrical between the two parties in the conversation. The difference between a websocket ‘client’ and a websocket ‘server’ is only in the means by which the two parties are connected. In this specification, we will say that a websocket client is a websocket endpoint that initiates a connection to a peer. We will say that a websocket server is a websocket endpoint that is published an awaits connections from peers. In most deployments, a websocket client will connect to only one websocket server, and a websocket server will accept connections from several clients.
  4. The annotation defines that the decorated method be called whenever a new client has connected to this endpoint. The container notifies the method after the connection has been established [WSC-21]. The decorated method can only have optional Session parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the newly created Session corresponding to the new connection [WSC-22]. If the method throws an error, the implementation must pass this error to the onError method of the endpoint together with the session.The annotation defines that the decorated method be called whenever a new client is about to be disconnected from this endpoint. The container notifies the method before the connection is brought down [WSC-25]. The decorated method can only have optional Session parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the about-to-be ended Session corresponding to the connection [WSC-26]. If the method throws an error, the implementation must pass this error to the onError method of the endpoint together with the session.The annotation defines that the decorated method be called whenever an error is generated on any of the connections to this endpoint. The decorated method can only have optional Session parameter, mandatory Throwable parameter and zero to n String parameters annotated with a @WebSocketPathSegment annotation as parameters. If the Session parameter is present, the implementation must pass in the Session in which the error occurred to the connection [WSC-XX]. The container must pass the error as the Throwable parameter to this method.
  5. The encoders parameter contains a (possibly empty) list of Java classes that are to act as encoder components for this endpoint. These classes must implement some form of the Encoder interface, and have public no-arg constructors and be visible within the classpath of the application that this websocket endpoint is part of. The implementation must attempt to encode application objects of matching parametrized type as the encoder when they are attempted to be sent using the RemoteEndpoint API.The decoders parameter contains a (possibly empty) list of Java classes that are to act as decoder components for this endpoint. These classes must implement some form of the Decoder interface, and have public no-arg constructors and be visible within the classpath of the application that this websocket endpoint is part of. The implementation must attempt to decode web socket messages using the first appropriate decoder in the list and pass the message in decoded object form to the websocket endpoint [WSC-17]. The implementation uses the willDecode() method on the decoder to determine if the Decoder will match the incoming message.
  6. The method it decorates may have a number of forms - The first String parameter in its parameter list must be called by the container using the String form of the incoming message, if in text form [WSC-29]. - The first byte parameter in its parameter list must be called by the container using the byte array form of the incoming message, if in binary form [WSC-30]. If the parameter list contains a Session parameter, the implementation must use the Session object corresponding to the connection on which the message arrived [WSC-31]. - The method may have zero to n String parameters annotated with @WebSocketPathParameter. The method may or may not have a return type. If the method has a return type, the implementation must treat this return object as a web socket message to be immediately sent back to the sender of the incoming message [WSC-32]. It uses the usual mechanism of checking its supply of encoders in order to handle return types other than String or byte[].
  7. The method it decorates may have a number of forms - The first String parameter in its parameter list must be called by the container using the String form of the incoming message, if in text form [WSC-29]. - The first byte parameter in its parameter list must be called by the container using the byte array form of the incoming message, if in binary form [WSC-30]. If the parameter list contains a Session parameter, the implementation must use the Session object corresponding to the connection on which the message arrived [WSC-31]. - The method may have zero to n String parameters annotated with @WebSocketPathParameter. The method may or may not have a return type. If the method has a return type, the implementation must treat this return object as a web socket message to be immediately sent back to the sender of the incoming message [WSC-32]. It uses the usual mechanism of checking its supply of encoders in order to handle return types other than String or byte[].