SlideShare a Scribd company logo
Building WebSocket Apps in
Java using JSR 356
Pankaj kSharma
rpspankaj2010@gmail.com
Resources
• Specification
• JSR: jcp.org/en/jsr/detail?id=356
• Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec
• FINAL: Part of Java EE 7
• Reference Implementation
• Tyrus: java.net/projects/tyrus
• Integrated in GlassFish 4
WebSocket
• WebSocket primer
• Getting Started with WebSocket
• Getting Started with server-client event
• Resources
Make the future java
• Web development has evolved considerably in the past few
years. We're beyond the static web pages linked together,
which caused browser refreshing and waiting for pages to load.
• Now, the demand is for completely dynamic applications
accessible from the web. These applications often need to be
as fast as possible and provide nearly real-time components.
• In this we will see how to develop event-driven web
applications using Reverse Ajax techniques.
Interactive Websites
1)HTTP is half duplex
2)HTTP is verbose
3)Hacks for server push
- Polling
- Long Polling
- Comet/Ajax
- complex, insufficient, wasteful.
Some Techniques To Achieve RTC
- Polling
- Long Polling
- Comet/Ajax
With different- different programming model.
They really been hacks.
People worked around the problem using:-
• Now we will go with Ajax, polling, streaming, Comet, and long
polling. Learn how to implement different Reverse Ajax
communication techniques, and explore the advantages and
disadvantages of each method.
• Ajax:- Asynchronous JavaScript and XML (Ajax), a browser
feature accessible in JavaScript, allows a script to make an
HTTP request to a website behind the scenes, without the need
for a page reload. Ajax has been around more than a decade.
• Though the name includes XML, you can transfer nearly
anything in an Ajax request. The most commonly used data is
JSON, which is close to JavaScript syntax and consumes less
bandwidth.
• Listing Example shows an example of an Ajax request to
retrieve a place's name from its postal code.
var url = http://www.geonames.org/postalCodeLookupJSON?postalcode='
+ $('#postalCode').val() + '&country=' + $('#country').val() + '&callback=?';
$.getJSON(url, function(data) {
$('#placeName').val(data.postalcodes[0].placeName);
});
• The timeline in Figure 1 shows how some polling requests
issued by the client, but no information is returned. The client
must wait for the next polling to get the two events received by
the server.
• Figure 1. Reverse Ajax with HTTP polling
• To implement polling in JavaScript, you can use setInterval to
periodically issue Ajax requests, as shown in example 2:
• Example 2. JavaScript polling
setInterval(function() {
$.getJSON('events',
function(events) {
console.log(events);
}); }, 2000);
• Ajax, polling or long polling is very limited, it does not scale and
does not provide low-latency communication (when events
arrive in the browser as soon as they arrive on the server).
• Comet is a web application model where a request is sent to
the server and kept alive for a long time, until a time-out or a
server event occurs.
• When the request is completed, another long-lived Ajax
request is sent to wait for other server events. With Comet,
web servers can send the data to the client, without having to
explicitly request it.
Comet:-
• Http is a very chatti protocol.
• When we are sending a request to the server there are very heavy
header as a part of the request.
• As a user, it is not visible to us but essentially the browser and client
is sending a full bunch of header that goes as the part of the
request and the same as the part of the response as well.
• The problem is, it is difficult and challenging for using http for real
time communication because there are so much overhead of the
protocol.
• Uncompressed request and response headers. Request headers
today vary in size from ~200 bytes to over 2KB. As applications
use more cookies and user agents expand features, typical
header sizes of 700-800 bytes is common.
and response headers associated with polling Example network
throughput for HTTP request
•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 second:
•Network throughput is (871 x 100,000) = 87,100,000 bytes =
696,800,000 bits per second (~665 Mbps)
- TCP based, bi-directional, full-duplex messaging.
•Originally proposed as part Html5.
•In 2011, the IETF standardized the WebSocket protocol as RFC 6455. Since
then, the majority of the Web browsers are implementing client APIs that
support the WebSocket protocol. Also, a number of Java libraries have been
developed that implement the WebSocket protocol.
•IETF(Internet Engineering Task Force) - defined protocol RFC-6455.
- Hand Shake
- Data Transfer
• W3C – defined JavaScript API to coordinate re-communication.
Then Exactly WebSocket comes in the picture.
• WebSocket is a protocol providing full-duplex communication 
channels over a single TCP connection. 
• The WebSocket protocol was standardized by the IETF as 
RFC 6455 in 2011, and the WebSocket API in Web IDL is being 
standardized by the W3C.
Establish a connection
Client
Handshake Request
Handshake Response
Server
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
ServerClient
Handshake Request
Handshake Response
Connected !
Establishing a Connection
Peer
(server)
Peer
(client)
Connected !
open open
close
message error
message
message message
message
Disconnected
WebSocket Lifecycle
WebSocket API
www.w3.org/TR/websockets/
• WebSocket is designed to be implemented in web browsers and 
web servers, but it can be used by any client or server application. The 
WebSocket Protocol is an independent TCP - based protocol. Its only 
relationship to HTTP is that its handshake is interpreted by HTTP servers as 
an Upgrade request.[1]
 
• The WebSocket protocol makes more interaction between a browser and a 
website, facilitating live content and the creation of real-time games.
• The life cycle of a WebSocket is easy to understand as well:
• Client sends the Server a handshake request in the form of a HTTP upgrade 
header with data about the WebSocket it’s attempting to connect to.
• The Server responds to the request with another HTTP header, this is the last 
time a HTTP header gets used in the WebSocket connection. If the handshake 
was successful, then server sends a HTTP header telling the client it’s switching 
to the WebSocket protocol.
• Now a constant connection is opened and the client and server can send any 
number of messages to each other until the connection is closed. These 
messages only have, about 2 bytes of overhead.
• Using the HTML5 WebSocket API
• Utilizing the WebSocket interface couldn't be simpler. To connect to an
end-point, just create a new WebSocket instance, providing the new
object with a URL that represents the end-point to which you wish to
connect, as shown in the following example.
• Note that a ws:// and wss:// prefix are proposed to indicate a
WebSocket and a secure WebSocket connection, respectively.
var myWebSocket = new WebSocket("ws://www.websockets.org");
• A WebSocket connection is established by upgrading from the HTTP
protocol to the WebSockets protocol during the initial handshake between
the client and the server. The connection itself is exposed via the
"onmessage" and "send" functions defined by the WebSocket interface.
• life-cycle as shown in the following example.
myWebSocket.onopen = function(evt) { alert("Connection open ..."); };
myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); };
myWebSocket.onclose = function(evt) { alert("Connection closed.");
• To send a message to the server, simply call "send" and provide the content
you wish to deliver. After sending the message, call "close" to terminate the
connection, as shown in the following example.
myWebSocket.send("Hello WebSockets!"); myWebSocket.close();
In Java JSR 356
• Java API for WebSocket, specifies the API that Java developers can use
when they want to integrate WebSockets into their applications.
• In general, two different programming models are supported:
• Annotation - driven. Using annotated POJOs, developers can interact with
the WebSocket lifecycle events.
• Interface - driven. Developers can implement the Endpoint interface and
the methods that interact with the lifecycle events.
Just look at the servlet example : Broadcasting.
JSR 356 is a part of the Java EE 7
(IETF (Internet Engineering Task Force)-defined protocol RFC-6455)
In Spring
Spring 4 has introduced the WebSocket API using which a
browser and web server can communicate over WebSocket
protocol.
• SockJS
SockJS is a java script library which provides websocket like object
for browsers. SockJS provides cross browser compatibility and
supports STOMP protocol to communicate with any message
broker. SockJS works in the way that we need to provide URL to
connect with message broker and then get the stomp client to
communicate.
• STOMP Protocol
STOMP is Simple(or Streaming) Text Oriented Messaging Protocol.
A STOMP client communicates to a message broker which
supports STOMP protocol.
• The protocol is broadly similar to HTTP, and works over TCP using
the following verbs:
• CONNECT
• SEND
• SUBSCRIBE
• UNSUBSCRIBE
• BEGIN
• COMMIT
• ABORT
• ACK
• NACK
• DISCONNECT
Q & A
References:-
• https://www.websocket.org/
• https://spring.io/guides/gs/messaging-stomp-websocket/
• http://docs.spring.io/spring/docs/current/spring-framework-
reference/html/websocket.html
• http://docs.spring.io/spring-boot/docs/current-
SNAPSHOT/reference/htmlsingle/#boot-documentation
• http://projects.spring.io/spring-boot/

More Related Content

What's hot

Netflix over Qos Enabled LTE Research Paper Final
Netflix over Qos Enabled LTE Research Paper FinalNetflix over Qos Enabled LTE Research Paper Final
Netflix over Qos Enabled LTE Research Paper Final
Ajit Kahaduwe
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
yht4ever
 

What's hot (20)

Python network programming
Python   network programmingPython   network programming
Python network programming
 
HTTP/2 Introduction
HTTP/2 IntroductionHTTP/2 Introduction
HTTP/2 Introduction
 
10 Things Every Developer Using RabbitMQ Should Know
10 Things Every Developer Using RabbitMQ Should Know10 Things Every Developer Using RabbitMQ Should Know
10 Things Every Developer Using RabbitMQ Should Know
 
gRPC Design and Implementation
gRPC Design and ImplementationgRPC Design and Implementation
gRPC Design and Implementation
 
Introduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQIntroduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQ
 
Rabbit MQ introduction
Rabbit MQ introductionRabbit MQ introduction
Rabbit MQ introduction
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
 
GRPC.pptx
GRPC.pptxGRPC.pptx
GRPC.pptx
 
An introduction to MQTT
An introduction to MQTTAn introduction to MQTT
An introduction to MQTT
 
Netflix over Qos Enabled LTE Research Paper Final
Netflix over Qos Enabled LTE Research Paper FinalNetflix over Qos Enabled LTE Research Paper Final
Netflix over Qos Enabled LTE Research Paper Final
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal Architecture
 
Getting started with MQTT - Virtual IoT Meetup presentation
Getting started with MQTT - Virtual IoT Meetup presentationGetting started with MQTT - Virtual IoT Meetup presentation
Getting started with MQTT - Virtual IoT Meetup presentation
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Introduction to WebSockets Presentation
Introduction to WebSockets PresentationIntroduction to WebSockets Presentation
Introduction to WebSockets Presentation
 
A 30-minute Introduction to NETCONF and YANG
A 30-minute Introduction to NETCONF and YANGA 30-minute Introduction to NETCONF and YANG
A 30-minute Introduction to NETCONF and YANG
 
AMQP
AMQPAMQP
AMQP
 
Rabbitmq an amqp message broker
Rabbitmq an amqp message brokerRabbitmq an amqp message broker
Rabbitmq an amqp message broker
 
Introduction to MQTT
Introduction to MQTTIntroduction to MQTT
Introduction to MQTT
 
Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPC
 
HTTP Presentation
HTTP Presentation HTTP Presentation
HTTP Presentation
 

Viewers also liked

FINAL PRESENTATION(Azad)
FINAL PRESENTATION(Azad)FINAL PRESENTATION(Azad)
FINAL PRESENTATION(Azad)
Md. Azad Hosen
 

Viewers also liked (19)

Rorys homework occupation
Rorys homework occupationRorys homework occupation
Rorys homework occupation
 
Giving Presentation
Giving PresentationGiving Presentation
Giving Presentation
 
Mastercoin: Reinventing Finance
Mastercoin: Reinventing FinanceMastercoin: Reinventing Finance
Mastercoin: Reinventing Finance
 
La internet
La internetLa internet
La internet
 
18 linen I love you cards
18 linen I love you cards18 linen I love you cards
18 linen I love you cards
 
Take Your Vacation Already
Take Your Vacation AlreadyTake Your Vacation Already
Take Your Vacation Already
 
LTE Core Network
LTE Core Network LTE Core Network
LTE Core Network
 
Gólgota nº 53 - Navidad 2016
Gólgota nº 53 - Navidad 2016Gólgota nº 53 - Navidad 2016
Gólgota nº 53 - Navidad 2016
 
20 habits make you happy (讓你快樂的20種習慣)
20 habits make you happy (讓你快樂的20種習慣)20 habits make you happy (讓你快樂的20種習慣)
20 habits make you happy (讓你快樂的20種習慣)
 
Intro to Marketing - Workshop 1 Intro to Marketing
Intro to Marketing - Workshop 1 Intro to MarketingIntro to Marketing - Workshop 1 Intro to Marketing
Intro to Marketing - Workshop 1 Intro to Marketing
 
Intro to Marketing - Workshop 5 Evaluation of Marketing Plans & Ethics
Intro to Marketing - Workshop 5 Evaluation of Marketing Plans & EthicsIntro to Marketing - Workshop 5 Evaluation of Marketing Plans & Ethics
Intro to Marketing - Workshop 5 Evaluation of Marketing Plans & Ethics
 
Angular2 compiler
Angular2 compilerAngular2 compiler
Angular2 compiler
 
Trees depicted in mayamatam
Trees depicted in  mayamatamTrees depicted in  mayamatam
Trees depicted in mayamatam
 
Hookedatinteraction - Nir Eyal
Hookedatinteraction - Nir EyalHookedatinteraction - Nir Eyal
Hookedatinteraction - Nir Eyal
 
Estudio del libro de Levítico
Estudio del libro de LevíticoEstudio del libro de Levítico
Estudio del libro de Levítico
 
FINAL PRESENTATION(Azad)
FINAL PRESENTATION(Azad)FINAL PRESENTATION(Azad)
FINAL PRESENTATION(Azad)
 
Balancing the tension between Lean and Agile
Balancing the tension between Lean and AgileBalancing the tension between Lean and Agile
Balancing the tension between Lean and Agile
 
Sales forecasting
Sales forecastingSales forecasting
Sales forecasting
 
Nfpa.58.2004 chapter 05
Nfpa.58.2004 chapter  05Nfpa.58.2004 chapter  05
Nfpa.58.2004 chapter 05
 

Similar to Web-Socket

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
Viktor Gamov
 
Programming WebSockets - OSCON 2010
Programming WebSockets - OSCON 2010Programming WebSockets - OSCON 2010
Programming WebSockets - OSCON 2010
sullis
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
clkao
 

Similar to Web-Socket (20)

WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
 
Websocket
WebsocketWebsocket
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
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Building real-time-collaborative-web-applications
Building real-time-collaborative-web-applicationsBuilding real-time-collaborative-web-applications
Building real-time-collaborative-web-applications
 
Real-Time with Flowdock
Real-Time with FlowdockReal-Time with Flowdock
Real-Time with Flowdock
 
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"
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at ScaleJUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Programming WebSockets - OSCON 2010
Programming WebSockets - OSCON 2010Programming WebSockets - OSCON 2010
Programming WebSockets - OSCON 2010
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
 
Servlets
ServletsServlets
Servlets
 
Server interaction with web socket protocol
Server interaction with web socket protocolServer interaction with web socket protocol
Server interaction with web socket protocol
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 

Web-Socket

  • 1.
  • 2. Building WebSocket Apps in Java using JSR 356 Pankaj kSharma rpspankaj2010@gmail.com
  • 3. Resources • Specification • JSR: jcp.org/en/jsr/detail?id=356 • Mailing Lists, JIRA, Archive: java.net/projects/websocket-spec • FINAL: Part of Java EE 7 • Reference Implementation • Tyrus: java.net/projects/tyrus • Integrated in GlassFish 4
  • 4. WebSocket • WebSocket primer • Getting Started with WebSocket • Getting Started with server-client event • Resources Make the future java
  • 5. • Web development has evolved considerably in the past few years. We're beyond the static web pages linked together, which caused browser refreshing and waiting for pages to load. • Now, the demand is for completely dynamic applications accessible from the web. These applications often need to be as fast as possible and provide nearly real-time components. • In this we will see how to develop event-driven web applications using Reverse Ajax techniques.
  • 6. Interactive Websites 1)HTTP is half duplex 2)HTTP is verbose 3)Hacks for server push - Polling - Long Polling - Comet/Ajax - complex, insufficient, wasteful. Some Techniques To Achieve RTC
  • 7. - Polling - Long Polling - Comet/Ajax With different- different programming model. They really been hacks. People worked around the problem using:-
  • 8. • Now we will go with Ajax, polling, streaming, Comet, and long polling. Learn how to implement different Reverse Ajax communication techniques, and explore the advantages and disadvantages of each method. • Ajax:- Asynchronous JavaScript and XML (Ajax), a browser feature accessible in JavaScript, allows a script to make an HTTP request to a website behind the scenes, without the need for a page reload. Ajax has been around more than a decade.
  • 9. • Though the name includes XML, you can transfer nearly anything in an Ajax request. The most commonly used data is JSON, which is close to JavaScript syntax and consumes less bandwidth. • Listing Example shows an example of an Ajax request to retrieve a place's name from its postal code. var url = http://www.geonames.org/postalCodeLookupJSON?postalcode=' + $('#postalCode').val() + '&country=' + $('#country').val() + '&callback=?'; $.getJSON(url, function(data) { $('#placeName').val(data.postalcodes[0].placeName); });
  • 10. • The timeline in Figure 1 shows how some polling requests issued by the client, but no information is returned. The client must wait for the next polling to get the two events received by the server. • Figure 1. Reverse Ajax with HTTP polling
  • 11. • To implement polling in JavaScript, you can use setInterval to periodically issue Ajax requests, as shown in example 2: • Example 2. JavaScript polling setInterval(function() { $.getJSON('events', function(events) { console.log(events); }); }, 2000);
  • 12. • Ajax, polling or long polling is very limited, it does not scale and does not provide low-latency communication (when events arrive in the browser as soon as they arrive on the server). • Comet is a web application model where a request is sent to the server and kept alive for a long time, until a time-out or a server event occurs. • When the request is completed, another long-lived Ajax request is sent to wait for other server events. With Comet, web servers can send the data to the client, without having to explicitly request it. Comet:-
  • 13. • Http is a very chatti protocol. • When we are sending a request to the server there are very heavy header as a part of the request. • As a user, it is not visible to us but essentially the browser and client is sending a full bunch of header that goes as the part of the request and the same as the part of the response as well. • The problem is, it is difficult and challenging for using http for real time communication because there are so much overhead of the protocol.
  • 14.
  • 15.
  • 16. • Uncompressed request and response headers. Request headers today vary in size from ~200 bytes to over 2KB. As applications use more cookies and user agents expand features, typical header sizes of 700-800 bytes is common.
  • 17. and response headers associated with polling Example network throughput for HTTP request •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 second: •Network throughput is (871 x 100,000) = 87,100,000 bytes = 696,800,000 bits per second (~665 Mbps)
  • 18. - TCP based, bi-directional, full-duplex messaging. •Originally proposed as part Html5. •In 2011, the IETF standardized the WebSocket protocol as RFC 6455. Since then, the majority of the Web browsers are implementing client APIs that support the WebSocket protocol. Also, a number of Java libraries have been developed that implement the WebSocket protocol. •IETF(Internet Engineering Task Force) - defined protocol RFC-6455. - Hand Shake - Data Transfer • W3C – defined JavaScript API to coordinate re-communication. Then Exactly WebSocket comes in the picture.
  • 20. Establish a connection Client Handshake Request Handshake Response Server
  • 21. 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
  • 22. Handshake Response HTTP/1.1 101 Switching Protocols Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
  • 24. Peer (server) Peer (client) Connected ! open open close message error message message message message Disconnected WebSocket Lifecycle
  • 27. • The life cycle of a WebSocket is easy to understand as well: • Client sends the Server a handshake request in the form of a HTTP upgrade  header with data about the WebSocket it’s attempting to connect to. • The Server responds to the request with another HTTP header, this is the last  time a HTTP header gets used in the WebSocket connection. If the handshake  was successful, then server sends a HTTP header telling the client it’s switching  to the WebSocket protocol. • Now a constant connection is opened and the client and server can send any  number of messages to each other until the connection is closed. These  messages only have, about 2 bytes of overhead.
  • 28. • Using the HTML5 WebSocket API • Utilizing the WebSocket interface couldn't be simpler. To connect to an end-point, just create a new WebSocket instance, providing the new object with a URL that represents the end-point to which you wish to connect, as shown in the following example. • Note that a ws:// and wss:// prefix are proposed to indicate a WebSocket and a secure WebSocket connection, respectively. var myWebSocket = new WebSocket("ws://www.websockets.org");
  • 29. • A WebSocket connection is established by upgrading from the HTTP protocol to the WebSockets protocol during the initial handshake between the client and the server. The connection itself is exposed via the "onmessage" and "send" functions defined by the WebSocket interface. • life-cycle as shown in the following example. myWebSocket.onopen = function(evt) { alert("Connection open ..."); }; myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); }; myWebSocket.onclose = function(evt) { alert("Connection closed."); • To send a message to the server, simply call "send" and provide the content you wish to deliver. After sending the message, call "close" to terminate the connection, as shown in the following example. myWebSocket.send("Hello WebSockets!"); myWebSocket.close();
  • 30. In Java JSR 356 • Java API for WebSocket, specifies the API that Java developers can use when they want to integrate WebSockets into their applications. • In general, two different programming models are supported: • Annotation - driven. Using annotated POJOs, developers can interact with the WebSocket lifecycle events. • Interface - driven. Developers can implement the Endpoint interface and the methods that interact with the lifecycle events. Just look at the servlet example : Broadcasting. JSR 356 is a part of the Java EE 7 (IETF (Internet Engineering Task Force)-defined protocol RFC-6455)
  • 31.
  • 32. In Spring Spring 4 has introduced the WebSocket API using which a browser and web server can communicate over WebSocket protocol.
  • 33. • SockJS SockJS is a java script library which provides websocket like object for browsers. SockJS provides cross browser compatibility and supports STOMP protocol to communicate with any message broker. SockJS works in the way that we need to provide URL to connect with message broker and then get the stomp client to communicate. • STOMP Protocol STOMP is Simple(or Streaming) Text Oriented Messaging Protocol. A STOMP client communicates to a message broker which supports STOMP protocol.
  • 34. • The protocol is broadly similar to HTTP, and works over TCP using the following verbs: • CONNECT • SEND • SUBSCRIBE • UNSUBSCRIBE • BEGIN • COMMIT • ABORT • ACK • NACK • DISCONNECT
  • 35. Q & A
  • 36. References:- • https://www.websocket.org/ • https://spring.io/guides/gs/messaging-stomp-websocket/ • http://docs.spring.io/spring/docs/current/spring-framework- reference/html/websocket.html • http://docs.spring.io/spring-boot/docs/current- SNAPSHOT/reference/htmlsingle/#boot-documentation • http://projects.spring.io/spring-boot/

Editor's Notes

  1. The protocol consists of an opening handshake followed by basic message framing, layered over TCP. In compliance with [RFC2616], header fields in the handshake may be sent by the client in any order, so the order in which different header fields are received is not significant. The leading line from the client follows the Request-Line format. The leading line from the server follows the Status-Line format. After the leading line in both cases come an unordered set of header fields. The "Request-URI" of the GET method [RFC2616] is used to identify the endpoint of the WebSocket connection, both to allow multiple domains to be served from one IP address and to allow multiple WebSocket endpoints to be served by a single server. The client includes the hostname in the |Host| header field of its handshake as per [RFC2616], so that both the client and the server can verify that they agree on which host is in use. HTTP defines an upgrade mechanism using Upgrade: header. This is typically used for to upgrade a client to a newer http protocol version or switch to a different protocol, such as HTTP over TLS. The Upgrade general-header allows the client to specify what additional communication protocols it supports and would like to use if the server finds it appropriate to switch protocols. This mechanism is used for upgrading to WebSocket. Additional header fields are used to select options in the WebSocket Protocol. Sec-WebSocket-Key is used in the creation of the server's handshake to indicate an acceptance of the connection. This helps ensure that the server does not accept connections from non-WebSocket clients (e.g. HTTP clients) that are being abused to send data to unsuspecting WebSocket servers. This prevents an attacker from tricking a WebSocket server by sending it carefully-crafted packets using |XMLHttpRequest| [XMLHttpRequest] or a |form| submission. To prove that the handshake was received, the server has to take two pieces of information and combine them to form a response. The first piece of information comes from the |Sec-WebSocket-Key| header field in the client handshake. For this header field, the server has to take the value (as present in the header field, e.g. the base64-encoded [RFC4648] version minus any leading and trailing whitespace), and concatenate this with the Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" in string form, which is unlikely to be used by network endpoints that do not understand the WebSocket protocol. A SHA-1 hash (160 bits), base64-encoded (see Section 4 of [RFC4648]), of this concatenation is then returned in the server's handshake. The |Sec-WebSocket-Protocol| request-header field can be used to indicate what subprotocols (application-level protocols layered over the WebSocket protocol) are acceptable to the client. The server selects one or none of the acceptable protocols and echoes that value in its handshake to indicate that it has selected that protocol. The |Sec-WebSocket-Version| header field in the client's handshake includes the version of the WebSocket protocol the client is attempting to communicate with. The |Origin| header field is used to protect against unauthorized cross-origin use of a WebSocket server by scripts using the |WebSocket| API in a Web browser. The |Sec-WebSocket-Extensions| header field is used in the WebSocket opening handshake. It is initially sent from the client to the server, and then subsequently sent from the server to the client, to agree on a set of protocol-level extensions to use for the duration of the connection.
  2. The handshake from the server is much simpler than the client handshake. The first line is an HTTP Status-Line, with the status code 101. Any status code other than 101 indicates that the WebSocket handshake has not completed and that the semantics of HTTP still apply. The headers follow the status code. The |Sec-WebSocket-Accept| header field indicates whether the server is willing to accept the connection. If present, this header field must include a hash of the client's nonce sent in |Sec-WebSocket-Key| along with a predefined GUID. Any other value must not be interpreted as an acceptance of the connection by the server. These fields are checked by the WebSocket client for scripted pages. If the |Sec-WebSocket-Accept| value does not match the expected value, if the header field is missing, or if the HTTP status code is not 101, the connection will not be established, and WebSocket frames will not be sent. Option fields can also be included. In this version of the protocol, the main option field is |Sec-WebSocket-Protocol|, which indicates the subprotocol that the server has selected. WebSocket clients verify that the server included one of the values that was specified in the WebSocket client's handshake. A server that speaks multiple subprotocols has to make sure it selects one based on the client's handshake and specifies it in its handshake. The WebSocket protocol specification defines Ping and Pong frames that can be used for keep-alive, heart-beats, network status probing, latency instrumentation, and so forth. These are not currently exposed in the API. Once the client and server have both sent their handshakes, and if the handshake was successful, then the data transfer part starts. This is a two-way communication channel where each side can, independently from the other, send data at will. The header fields in the handshake may be sent by the client in any order, so the order in which different header fields are received is not significant.
  3. After a successful handshake, clients and servers transfer data back and forth in conceptual units referred to in this specification as "messages". On the wire, a message is composed of one or more frames. The WebSocket message does not necessarily correspond to a particular network layer framing, as a fragmented message may be coalesced or split by an intermediary. A frame has an associated type. Each frame belonging to the same message contains the same type of data. Broadly speaking, there are types for textual data (which is interpreted as UTF-8 [RFC3629] text), binary data (whose interpretation is left up to the application), and control frames (which are not intended to carry data for the application but instead for protocol-level signaling, such as to signal that the connection should be closed). This version of the protocol defines six frame types and leaves ten reserved for future use. Closing Handshake: The closing handshake is far simpler than the opening handshake. Either peer can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in Section 5.5.1). Upon receiving such a frame, the other peer sends a Close frame in response, if it hasn't already sent one. Upon receiving _that_ control frame, the first peer then closes the connection, safe in the knowledge that no further data is forthcoming. After sending a control frame indicating the connection should be closed, a peer does not send any further data; after receiving a control frame indicating the connection should be closed, a peer discards any further data received. It is safe for both peers to initiate this handshake simultaneously. The closing handshake is intended to complement the TCP closing handshake (FIN/ACK), on the basis that the TCP closing handshake is not always reliable end-to-end, especially in the presence of intercepting proxies and other intermediaries. By sending a Close frame and waiting for a Close frame in response, certain cases are avoided where data may be unnecessarily lost. For instance, on some platforms, if a socket is closed with data in the receive queue, a RST packet is sent, which will then cause recv() to fail for the party that received the RST, even if there was data waiting to be read.