SlideShare a Scribd company logo
JEE - WebSockets
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
Lecture 6 - WebSockets
• Web communications technologies
• Web Socket methodology
• Web Socket APIs
• JavaScript API
• Java API for WebSockets
2 JEE - WebSockets
Interactions over HTTP
• It is half-duplex
• It is verbose
• Server push issue
• Frequent Polling
• Long Polling
• Chunked Encoding
• Applet & Flash
3 JEE - WebSockets
Frequent polling
4
Long Polling
5
Chunked Encoding
6 JEE - WebSockets
Applets & Adobe Flash
7
Interactions through WebSockets
• It is TCP-based
• Supports bi-directional, full-duplex messaging
• Two phases
• Handshake
• Data Transfer
8 JEE - WebSockets
Handshake
9 JEE - WebSockets
client Server
• Agreeing on upgrade to WebSocket
• No response means no handshake
Handshake Request (over HTTP)
Handshake Response (over HTTP)
WebSocket Upgrade Request
GET /webSocketEndpoint HTTP/1.1
Host: www.ece.fr
Connection: Upgrade
Upgrade: websocket
Origin: http://ece.fr
Sec-WebSocket-Key: s3JKEMbDL4ErLkh9GBlXDx==
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: chat
HTTP/1.1 101 Switching Protocols
Server: Apache 2.4
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
10
client key
hashed value
Server
Establishing a connection
• Once connected both client and server become peers
with equal rights for interaction and closing the
session.
11 JEE - WebSockets
client Server
Handshake Request (over HTTP)
Handshake Response (over HTTP)
Connected
Full-duplex WebSocket Communications
12 JEE - WebSockets
client Server
message
Connected
message
message
message
message
message
Disconnected
close
Where is it used?
• Chat
• Online games
• Live stock/News tickers
• HD Video Streaming
• Bulk transactional data transfer
• Real time monitoring for remote systems
13 JEE - WebSockets
WebSocket Interface in API
14
APIs for WebSocket
• Javascript API
• Client Only
var connection = new WebSocket(uri);
• JEE
• Client API
• foundational API for data transfer
• Server API
• additional constructs for managing handshakes,
server endpoints, server container, etc.
15 JEE - WebSockets
Javascript API - readyState Attribute
• CONNECTING (numeric value 0)
• When object is created. The connection has not yet established.
• OPEN (numeric value 1)
• The WebSocket connection is established and communication is
possible.
• CLOSING (numeric value 2)
• The connection is going through the closing handshake, or the
close() method has been invoked.
• CLOSED (numeric value 3)
• The connection has been closed or could not be opened.
if(connection.readyState == WebSocket.OPEN) {
/* do something */ }
16 JEE - WebSockets
Javascript API - events
connection.onopen = function(event) { }
• readyState changes from CONNECTING to OPEN
connection.onclose = function(event) { }
• readyState changes from CLOSING to CLOSED
connection.onerror = function(event) { }
• In case of client-side errors
connection.onmessage = function(event) { }
• On arrival of a message
17 JEE - WebSockets
JavaScriptAPI - onmessage()
• It has a data property
• String: message = text
• Blob: message = binary, binaryType = “blob”
• ArrayBuffer: message = binary, binaryType = “arraybuffer”
• binaryType is a property of web socket
var socket = new WebSocket(“ws://localhost:8080/BasicWebSocketExample/
echo");
socket.onmessage = function(event){
if(event.data instanceof Blob){
console.log("Blob message received", event.data);
var blob = new Blob(event.data);
}
}
18 JEE - WebSockets
Javascript API - Other methods
• close()
• optional code & optional reason string
• send()
• accepts string, blob, ArrayBuffer, ArraryBufferView
connection.onopen = function() {
var intervalId = window.setInterval(function() {
if(connection.readyState != WebSocket.OPEN) {
window.clearInterval(intervalId);
return;
}
if(connection.bufferedAmount == 0)
connection.send(updatedModelData);
}, 50);
}
19 JEE - WebSockets
Simple Example - Client side
• Used the wildfly archetype used in last TP
wildfly-javaee7-webapp-blank-archetype
• POM (added dependencies)
<dependency>
<groupId>org.jboss.spec.javax.websocket</groupId>
<artifactId>jboss-websocket-api_1.0_spec</artifactId>
<scope>provided</scope>
</dependency>
20
Simple Example - Client side
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title>Echo WebSocket</title>
<script type="text/javascript">
var socket = new WebSocket("ws://localhost:8080/BasicWebSocketExample/
echo");
//Event handler for the WebSocket connection opening
socket.onopen = function(event) {
console.log("Connection open...");};
//Event handler for closed connections
socket.onclose = function(event) {
console.log("Connection closed", event);};
//Event handler for errors in the WebSocket object
socket.onerror = function(event) {
console.log("WebSocket Error: " , event);};
21
Simple Example - Client side
//Event handler for the WebSocket message reception
socket.onmessage = function(event){
alert(event.data)
if(typeof event.data === "string"){
console.log("String message received", event, event.data);
} else {
console.log("Other message received", event, event.data);
}
}
</script>
</head>
<body>
<button onclick='socket.send("hey dude")'>send</button>
</body>
</html>
Note: Server side in the coming slides ….
22
JEE Client API - The Process
• The process for creating and deploying a WebSocket
endpoint follows.
• 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.
• Two ways to create endpoints
• Programmatic endpoints
• Annotated endpoints
23 JEE - WebSockets
Programmatic Endpoints
• Endpoint is created by extending Endpoint class
• Three methods to override
• onOpen, onClose and onError
• onOpen is an abstract method (must implement)
• onOpen has session parameter which is
responsible for communication
• getBasicRemote give the remote end
• addMessageHandler method of the session parameter
is used to register message handlers
• message handler is implemented as anonymous class
24 JEE - WebSockets
Programmatic Endpoints
package com.ece.jee;
public class EchoEndPoint extends Endpoint {
@Override
public void onOpen(final Session session, EndpointConfig config) {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
25
Annotated Endpoints
• Deployment is easy through annotations
• Annotations mark the respective methods for each
event in the lifecycle
• onOpen
• onMessage
• onError
• onClose
26 JEE - WebSockets
Endpoint Lifecycle Annotations
27
Annotation Event Example
onOpen Connection
opened
@OnOpen
public void open(Session session,
EndpointConfig conf) { }
onMessage Message
received
@OnMessage
public void message(Session session,
String msg) { }
onError Connection
error
@OnError
public void error(Session session,
Throwable error) { }
onClose Connection
closed
@OnClose
public void close(Session session,
CloseReason reason) { }
Sending Messages
• Get session object from the annotated methods
• Get the remoteEndPoint object (either of two)
Session.getBasicRemote
Session.getAsyncRemote
• Send messages
void RemoteEndpoint.Basic.sendText(String text)
void RemoteEndpoint.Basic.sendBinary(ByteBuffer data)
void RemoteEndpoint.sendPing(ByteBuffer appData)
void RemoteEndpoint.sendPong(ByteBuffer appData)
28 JEE - WebSockets
Simple Example - (cntd) Server Side
@ServerEndpoint("/echo")
public class Echo {
private Session session;
@OnOpen
public void connect(Session session) {
this.session = session;
System.out.println("session opened: " + session);
}
@OnClose
public void close() {
this.session = null;
System.out.println("session closed: " + session);
}
@OnMessage
public void onMessage(String msg) {
System.out.println("on message is called");
this.session.getAsyncRemote().sendText("Message from Server:" + msg);
}
}
29
Sending message to all endpoints
@ServerEndpoint("/echoAll")
public class EchoAllEndPoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
for (Session sess : session.getOpenSessions()) {
if (sess.isOpen())
sess.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
30 JEE - WebSockets
Receiving messages
• onMessage annotations are used to handle incoming
messages
• At most three methods with this annotation are
allowed
• text
• binary
• pong
31 JEE - WebSockets
Receiving messages
@ServerEndpoint("/receive")
public class ReceiveEndPoint {
@OnMessage
public void textMessage(Session session, String msg) {
System.out.println("Text message: " + msg);
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: "
+ msg.getApplicationData().toString());
}
}
32
33 JEE - WebSockets

More Related Content

PDF
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
PDF
Lecture 5 JSTL, custom tags, maven
PDF
Lecture 3: Servlets - Session Management
ODP
Spring 4 final xtr_presentation
PDF
Spring 4 Web App
PPT
Java Server Faces (JSF) - Basics
PPT
J2EE - JSP-Servlet- Container - Components
PPS
Jdbc api
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 5 JSTL, custom tags, maven
Lecture 3: Servlets - Session Management
Spring 4 final xtr_presentation
Spring 4 Web App
Java Server Faces (JSF) - Basics
J2EE - JSP-Servlet- Container - Components
Jdbc api

What's hot (17)

PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PPT
Spring MVC
PDF
the Spring 4 update
PPSX
Struts 2 - Introduction
PPT
Java servlet life cycle - methods ppt
PPT
JAX-WS Basics
PPSX
JSP - Part 1
PDF
Java Web Programming [6/9] : MVC
PPT
Data Access with JDBC
PDF
JDBC in Servlets
PPSX
Spring - Part 4 - Spring MVC
DOC
PPT
Java Servlets
PPTX
Spring & hibernate
PPTX
JSP - Java Server Page
JAVA EE DEVELOPMENT (JSP and Servlets)
Spring MVC
the Spring 4 update
Struts 2 - Introduction
Java servlet life cycle - methods ppt
JAX-WS Basics
JSP - Part 1
Java Web Programming [6/9] : MVC
Data Access with JDBC
JDBC in Servlets
Spring - Part 4 - Spring MVC
Java Servlets
Spring & hibernate
JSP - Java Server Page
Ad

Viewers also liked (20)

PDF
Lecture 2: Servlets
PDF
Lecture 9 - Java Persistence, JPA 2
PDF
Lecture 10 - Java Server Faces (JSF)
PDF
Lecture 7 Web Services JAX-WS & JAX-RS
PDF
Lecture 1: Introduction to JEE
PDF
Lecture 8 Enterprise Java Beans (EJB)
PDF
Tutorial 4 - Basics of Digital Photography
PDF
TNAPS 3 Installation
PPT
Ejb in java. part 1.
PDF
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
PDF
Apache Lucene + Hibernate = Hibernate Search
PPT
JMS Introduction
PPT
Java Server Faces (JSF) - advanced
PDF
The Modern Java Web Developer Bootcamp - Devoxx 2013
PDF
Introduction to WebSockets
KEY
The HTML5 WebSocket API
PDF
Enterprise Java Beans - EJB
PPT
PDF
JMS - Java Messaging Service
PPT
Domain object model
Lecture 2: Servlets
Lecture 9 - Java Persistence, JPA 2
Lecture 10 - Java Server Faces (JSF)
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 1: Introduction to JEE
Lecture 8 Enterprise Java Beans (EJB)
Tutorial 4 - Basics of Digital Photography
TNAPS 3 Installation
Ejb in java. part 1.
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
Apache Lucene + Hibernate = Hibernate Search
JMS Introduction
Java Server Faces (JSF) - advanced
The Modern Java Web Developer Bootcamp - Devoxx 2013
Introduction to WebSockets
The HTML5 WebSocket API
Enterprise Java Beans - EJB
JMS - Java Messaging Service
Domain object model
Ad

Similar to Lecture 6 Web Sockets (20)

PDF
Nodejs and WebSockets
PPTX
Enhancing Mobile User Experience with WebSocket
PDF
HTML5/JavaScript Communication APIs - DPC 2014
PPTX
vlavrynovych - WebSockets Presentation
PDF
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
PPTX
Html5 websockets
PPTX
Web sockets in Java
PDF
GWT Web Socket and data serialization
PPTX
WebSockets in JEE 7
PDF
ITI006En-AJAX
PDF
Spring Web Services: SOAP vs. REST
PPTX
Asynchronous Web Programming with HTML5 WebSockets and Java
PDF
softshake 2014 - Java EE
PDF
Speed up your Web applications with HTML5 WebSockets
KEY
Socket.io
PDF
Unity and WebSockets
KEY
Websockets - DevFestX May 19, 2012
PDF
Pushing Datatothe Browserwith Comet Ajax W
PPT
PDF
soft-shake.ch - Hands on Node.js
Nodejs and WebSockets
Enhancing Mobile User Experience with WebSocket
HTML5/JavaScript Communication APIs - DPC 2014
vlavrynovych - WebSockets Presentation
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Html5 websockets
Web sockets in Java
GWT Web Socket and data serialization
WebSockets in JEE 7
ITI006En-AJAX
Spring Web Services: SOAP vs. REST
Asynchronous Web Programming with HTML5 WebSockets and Java
softshake 2014 - Java EE
Speed up your Web applications with HTML5 WebSockets
Socket.io
Unity and WebSockets
Websockets - DevFestX May 19, 2012
Pushing Datatothe Browserwith Comet Ajax W
soft-shake.ch - Hands on Node.js

More from Fahad Golra (9)

PDF
Seance 4- Programmation en langage C
PDF
Seance 3- Programmation en langage C
PDF
Seance 2 - Programmation en langage C
PDF
Seance 1 - Programmation en langage C
PDF
Tutorial 3 - Basics of Digital Photography
PDF
Tutorial 2 - Basics of Digital Photography
PDF
Tutorial 1 - Basics of Digital Photography
PPTX
Deviation Detection in Process Enactment
PPTX
Meta l metacase tools & possibilities
Seance 4- Programmation en langage C
Seance 3- Programmation en langage C
Seance 2 - Programmation en langage C
Seance 1 - Programmation en langage C
Tutorial 3 - Basics of Digital Photography
Tutorial 2 - Basics of Digital Photography
Tutorial 1 - Basics of Digital Photography
Deviation Detection in Process Enactment
Meta l metacase tools & possibilities

Recently uploaded (20)

PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Digital Strategies for Manufacturing Companies
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPT
Introduction Database Management System for Course Database
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Introduction to Artificial Intelligence
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
ai tools demonstartion for schools and inter college
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administraation Chapter 3
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Digital Strategies for Manufacturing Companies
Design an Analysis of Algorithms I-SECS-1021-03
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Introduction Database Management System for Course Database
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Introduction to Artificial Intelligence
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Wondershare Filmora 15 Crack With Activation Key [2025
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
ai tools demonstartion for schools and inter college
How Creative Agencies Leverage Project Management Software.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Odoo POS Development Services by CandidRoot Solutions
PTS Company Brochure 2025 (1).pdf.......
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administraation Chapter 3

Lecture 6 Web Sockets

  • 1. JEE - WebSockets Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2. Lecture 6 - WebSockets • Web communications technologies • Web Socket methodology • Web Socket APIs • JavaScript API • Java API for WebSockets 2 JEE - WebSockets
  • 3. Interactions over HTTP • It is half-duplex • It is verbose • Server push issue • Frequent Polling • Long Polling • Chunked Encoding • Applet & Flash 3 JEE - WebSockets
  • 6. Chunked Encoding 6 JEE - WebSockets
  • 7. Applets & Adobe Flash 7
  • 8. Interactions through WebSockets • It is TCP-based • Supports bi-directional, full-duplex messaging • Two phases • Handshake • Data Transfer 8 JEE - WebSockets
  • 9. Handshake 9 JEE - WebSockets client Server • Agreeing on upgrade to WebSocket • No response means no handshake Handshake Request (over HTTP) Handshake Response (over HTTP)
  • 10. WebSocket Upgrade Request GET /webSocketEndpoint HTTP/1.1 Host: www.ece.fr Connection: Upgrade Upgrade: websocket Origin: http://ece.fr Sec-WebSocket-Key: s3JKEMbDL4ErLkh9GBlXDx== Sec-WebSocket-Version: 13 Sec-WebSocket-Protocol: chat HTTP/1.1 101 Switching Protocols Server: Apache 2.4 Connection: Upgrade Upgrade: websocket Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat 10 client key hashed value Server
  • 11. Establishing a connection • Once connected both client and server become peers with equal rights for interaction and closing the session. 11 JEE - WebSockets client Server Handshake Request (over HTTP) Handshake Response (over HTTP) Connected
  • 12. Full-duplex WebSocket Communications 12 JEE - WebSockets client Server message Connected message message message message message Disconnected close
  • 13. Where is it used? • Chat • Online games • Live stock/News tickers • HD Video Streaming • Bulk transactional data transfer • Real time monitoring for remote systems 13 JEE - WebSockets
  • 15. APIs for WebSocket • Javascript API • Client Only var connection = new WebSocket(uri); • JEE • Client API • foundational API for data transfer • Server API • additional constructs for managing handshakes, server endpoints, server container, etc. 15 JEE - WebSockets
  • 16. Javascript API - readyState Attribute • CONNECTING (numeric value 0) • When object is created. The connection has not yet established. • OPEN (numeric value 1) • The WebSocket connection is established and communication is possible. • CLOSING (numeric value 2) • The connection is going through the closing handshake, or the close() method has been invoked. • CLOSED (numeric value 3) • The connection has been closed or could not be opened. if(connection.readyState == WebSocket.OPEN) { /* do something */ } 16 JEE - WebSockets
  • 17. Javascript API - events connection.onopen = function(event) { } • readyState changes from CONNECTING to OPEN connection.onclose = function(event) { } • readyState changes from CLOSING to CLOSED connection.onerror = function(event) { } • In case of client-side errors connection.onmessage = function(event) { } • On arrival of a message 17 JEE - WebSockets
  • 18. JavaScriptAPI - onmessage() • It has a data property • String: message = text • Blob: message = binary, binaryType = “blob” • ArrayBuffer: message = binary, binaryType = “arraybuffer” • binaryType is a property of web socket var socket = new WebSocket(“ws://localhost:8080/BasicWebSocketExample/ echo"); socket.onmessage = function(event){ if(event.data instanceof Blob){ console.log("Blob message received", event.data); var blob = new Blob(event.data); } } 18 JEE - WebSockets
  • 19. Javascript API - Other methods • close() • optional code & optional reason string • send() • accepts string, blob, ArrayBuffer, ArraryBufferView connection.onopen = function() { var intervalId = window.setInterval(function() { if(connection.readyState != WebSocket.OPEN) { window.clearInterval(intervalId); return; } if(connection.bufferedAmount == 0) connection.send(updatedModelData); }, 50); } 19 JEE - WebSockets
  • 20. Simple Example - Client side • Used the wildfly archetype used in last TP wildfly-javaee7-webapp-blank-archetype • POM (added dependencies) <dependency> <groupId>org.jboss.spec.javax.websocket</groupId> <artifactId>jboss-websocket-api_1.0_spec</artifactId> <scope>provided</scope> </dependency> 20
  • 21. Simple Example - Client side <!DOCTYPE html> <html><head> <meta charset="UTF-8"> <title>Echo WebSocket</title> <script type="text/javascript"> var socket = new WebSocket("ws://localhost:8080/BasicWebSocketExample/ echo"); //Event handler for the WebSocket connection opening socket.onopen = function(event) { console.log("Connection open...");}; //Event handler for closed connections socket.onclose = function(event) { console.log("Connection closed", event);}; //Event handler for errors in the WebSocket object socket.onerror = function(event) { console.log("WebSocket Error: " , event);}; 21
  • 22. Simple Example - Client side //Event handler for the WebSocket message reception socket.onmessage = function(event){ alert(event.data) if(typeof event.data === "string"){ console.log("String message received", event, event.data); } else { console.log("Other message received", event, event.data); } } </script> </head> <body> <button onclick='socket.send("hey dude")'>send</button> </body> </html> Note: Server side in the coming slides …. 22
  • 23. JEE Client API - The Process • The process for creating and deploying a WebSocket endpoint follows. • 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. • Two ways to create endpoints • Programmatic endpoints • Annotated endpoints 23 JEE - WebSockets
  • 24. Programmatic Endpoints • Endpoint is created by extending Endpoint class • Three methods to override • onOpen, onClose and onError • onOpen is an abstract method (must implement) • onOpen has session parameter which is responsible for communication • getBasicRemote give the remote end • addMessageHandler method of the session parameter is used to register message handlers • message handler is implemented as anonymous class 24 JEE - WebSockets
  • 25. Programmatic Endpoints package com.ece.jee; public class EchoEndPoint extends Endpoint { @Override public void onOpen(final Session session, EndpointConfig config) { session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { e.printStackTrace(); } } }); } } 25
  • 26. Annotated Endpoints • Deployment is easy through annotations • Annotations mark the respective methods for each event in the lifecycle • onOpen • onMessage • onError • onClose 26 JEE - WebSockets
  • 27. Endpoint Lifecycle Annotations 27 Annotation Event Example onOpen Connection opened @OnOpen public void open(Session session, EndpointConfig conf) { } onMessage Message received @OnMessage public void message(Session session, String msg) { } onError Connection error @OnError public void error(Session session, Throwable error) { } onClose Connection closed @OnClose public void close(Session session, CloseReason reason) { }
  • 28. Sending Messages • Get session object from the annotated methods • Get the remoteEndPoint object (either of two) Session.getBasicRemote Session.getAsyncRemote • Send messages void RemoteEndpoint.Basic.sendText(String text) void RemoteEndpoint.Basic.sendBinary(ByteBuffer data) void RemoteEndpoint.sendPing(ByteBuffer appData) void RemoteEndpoint.sendPong(ByteBuffer appData) 28 JEE - WebSockets
  • 29. Simple Example - (cntd) Server Side @ServerEndpoint("/echo") public class Echo { private Session session; @OnOpen public void connect(Session session) { this.session = session; System.out.println("session opened: " + session); } @OnClose public void close() { this.session = null; System.out.println("session closed: " + session); } @OnMessage public void onMessage(String msg) { System.out.println("on message is called"); this.session.getAsyncRemote().sendText("Message from Server:" + msg); } } 29
  • 30. Sending message to all endpoints @ServerEndpoint("/echoAll") public class EchoAllEndPoint { @OnMessage public void onMessage(Session session, String msg) { try { for (Session sess : session.getOpenSessions()) { if (sess.isOpen()) sess.getBasicRemote().sendText(msg); } } catch (IOException e) { e.printStackTrace(); } } } 30 JEE - WebSockets
  • 31. Receiving messages • onMessage annotations are used to handle incoming messages • At most three methods with this annotation are allowed • text • binary • pong 31 JEE - WebSockets
  • 32. Receiving messages @ServerEndpoint("/receive") public class ReceiveEndPoint { @OnMessage public void textMessage(Session session, String msg) { System.out.println("Text message: " + msg); } @OnMessage public void binaryMessage(Session session, ByteBuffer msg) { System.out.println("Binary message: " + msg.toString()); } @OnMessage public void pongMessage(Session session, PongMessage msg) { System.out.println("Pong message: " + msg.getApplicationData().toString()); } } 32
  • 33. 33 JEE - WebSockets