SlideShare a Scribd company logo
WebSockets in Java
From n00b to pro

22 Dec 2013, JavaDay, Pance Cavkovski
Theory

- WebSocket is a protocol providing full-duplex
communications over a single TCP
connection.
- Standardized by IETF as RFC 6455
- Designed to be implemented in web browsers
and web servers
- HTTP Upgrade request for initiating
connection

* Contents from Wikipedia: http://en.wikipedia.org/wiki/Web_sockets

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept:
HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

Netcetera | 2
Sample application

https://github.com/hsilomedus/web-sockets-samples
Netcetera | 3
public static void main(String[] args)
JavaWebSocket (web-socket-samples/javawebsockets)
public class Main extends WebSocketServer {
public Main() {
super(new InetSocketAddress(8887));
}
@Override
public void onOpen(WebSocket conn,
ClientHandshake handshake) {
//Handle new connection here
conn.send(“{”connected”: true}”);
}
@Override
public void onMessage(WebSocket conn,
String message) {
//Handle client received message here
}
* https://github.com/TooTallNate/Java-WebSocket

@Override
public void onClose(WebSocket conn, int code,
String reason, boolean remote) {
//Handle closing connection here
}
@Override
public void onError(WebSocket conn,
Exception exc) {
//Handle error during transport here
}
public static void main(String[] args) {
Main server = new Main();
server.start();
}
}
Netcetera | 4
Client
JavaScript WebSocket API
var socket = new WebSocket(“ws://localhost:8887”);
socket.onopen = function() {
//event handler when the connection has been established
socket.send(nickname);
};
socket.onmessage = function(message) {
//event handler when data has been received from the server
alert(message.data);
};
socket.onclose = function() {
//event handler when the socket has been properly closed
}
socket.onerror = function() {
//event handler when an error has occurred during communication
}
Netcetera | 5
Java EE 7: JSR 356 + Java7
Tomcat (>7.0.43) (web-socket-samples/eesockets)
@ServerEndpoint(“/chat”)
public class EESocketChatEndpoint {
@OnOpen
public void onOpen(Session session) {
//Handle new connection here
session.getBasicRemote()
.sendText(“{”connected”: true}”);
}
@OnMessage
public void onMessage(String message) {
//Handle client received message here
}

@OnClose
public void onClose(Session session,
CloseReason reason) {
//Handle closing connection here
}
@OnError
public void onError(Session session,
Throwable throwable) {
//Handle error during transport here
}
}

* JSR 356, Java API for WebSocket: http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html (javax.websocket.*)

Netcetera | 6
Client
Pretty much the same JavaScript WebSocket API
var socket = new WebSocket(”ws://” + document.domain + “:8080/eesockets/chat”);
socket.onopen = function() {
//event handler when the connection has been established
socket.send(nickname);
};
socket.onmessage = function(message) {
//event handler when data has been received from the server
alert(message.data);
};
socket.onclose = function() {
//event handler when the socket has been properly closed
}
socket.onerror = function() {
//event handler when an error has occurred during communication
}
Netcetera | 7
Spring4
Static dispatcher servlet config
public class DispatcherServletInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() { return null; }
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
@Override
protected String[] getServletMappings() { return new String[]{“/”}; }
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setInitParameter(“dispatchOptionsRequest”, “true”);
}
}
Netcetera | 8
Spring4
Static context config
@Configuration
@EnableWebMvc
@EnableWebSocket
@ComponentScan(basePackages={“mk.hsilomedus.springsockets.service”})
public class WebConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatWenSocketHandler(), “/chat”).withSockJS();
}
@Bean
public WebSocketHandler chatWebSocketHandler() {
return new PerConnectionWebSocketHandler(ChatWebSocketHandler.class);
}
@Override
public void configureDefaultServletHandling(DefaultServerHandlerConfigurer configurer) {
configurer.enable();
}
Netcetera | 9
}
Spring4
WebSocketHandler (web-socket-samples/springsockets)
public class ChatWebSocketHandler extends
TextWebSocketHandler {
@Override
public void afterConnectionEstablished(
WebSocketSession session) {
//Handle new connection here
session.sendMessage(
“{”connected”: true}”);
}
@Override
public void handleTextMessage(
WebSocketSession session,
TextMessage message) {
//Handle message.getPayload() here
}
* http://blog.gopivotal.com/products/websocket-architecture-in-spring-4-0

@Override
public void afterConnectionClosed(
WebSocketSession session,
CloseStatus status) {
//Handle closing connection here
}
@Override
public void handleTransportError(
WebSocketSession session,
Throwable exception) {
//Handle error during transport here
}
}

Netcetera | 10
Client
SockJS
//I can now fallback to longpoll and do IE9!!!
var socket = new SockJS(”http://” + document.domain + “:8080/springsockets/chat”);
socket.onopen = function() {
//event handler when the connection has been established
socket.send(nickname);
};
socket.onmessage = function(message) {
//event handler when data has been received from the server
alert(message.data);
};
socket.onclose = function() {
//event handler when the socket has been properly closed
}
socket.onerror = function() {
//event handler when an error has occurred during communication
}
Netcetera | 11
socket.close();
Thanks for your attention
- The whole source code is available on github:
https://github.com/hsilomedus/web-sockets-samples
- /javawebsockets – with the JavaWebSocket library
- /eesockets – with Tomcat 7.0.47
- /springsockets – with Spring4 RC2 and Tomcat 7.0.47
- All three are eclipse projects running on Java7
- Questions?
- https://twitter.com/hsilomedus, http://hsilomedus.me/
Netcetera | 12

More Related Content

PDF
WebSockets with Spring 4
PPTX
Asynchronous Web Programming with HTML5 WebSockets and Java
PPTX
Websockets and SockJS, Real time chatting
PPTX
Spring + WebSocket integration
KEY
Pushing the web — WebSockets
PDF
Realtime web application with java
PPT
WebSockets and Java
PDF
WebSockets wiith Scala and Play! Framework
WebSockets with Spring 4
Asynchronous Web Programming with HTML5 WebSockets and Java
Websockets and SockJS, Real time chatting
Spring + WebSocket integration
Pushing the web — WebSockets
Realtime web application with java
WebSockets and Java
WebSockets wiith Scala and Play! Framework

What's hot (20)

PDF
Building Real-Time Applications with Android and WebSockets
KEY
The HTML5 WebSocket API
PPTX
Php push notifications
PPT
HTML5 WebSocket: The New Network Stack for the Web
PPTX
Intro to WebSockets
ZIP
Websocket protocol overview
PPTX
Websockets on the JVM: Atmosphere to the rescue!
PPTX
Reverse ajax in 2014
PPTX
PDF
GWT Web Socket and data serialization
KEY
Dancing with websocket
PPS
J web socket
PDF
Using Websockets with Play!
PPTX
The Atmosphere Framework
PPTX
WebSockets in JEE 7
ODP
Using Websockets in Play !
PPTX
Large scale web socket system with AWS and Web socket
PPT
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
PPTX
Building WebSocket and Server Side Events Applications using Atmosphere
PPTX
Websockets in Node.js - Making them reliable and scalable
Building Real-Time Applications with Android and WebSockets
The HTML5 WebSocket API
Php push notifications
HTML5 WebSocket: The New Network Stack for the Web
Intro to WebSockets
Websocket protocol overview
Websockets on the JVM: Atmosphere to the rescue!
Reverse ajax in 2014
GWT Web Socket and data serialization
Dancing with websocket
J web socket
Using Websockets with Play!
The Atmosphere Framework
WebSockets in JEE 7
Using Websockets in Play !
Large scale web socket system with AWS and Web socket
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
Building WebSocket and Server Side Events Applications using Atmosphere
Websockets in Node.js - Making them reliable and scalable
Ad

Viewers also liked (20)

PDF
Java sockets
PPT
Present Continuous
PDF
Garbage Collection without Paging
PDF
Open and online: connections, community and reality
PPTX
Copenhagen Open For Connections Dias
PPTX
Multithreaded programming
PPTX
Insert a Page Number in the Running Head
PPTX
Presentiaon task sheduling first come first serve FCFS
PPS
The Look Of Love
PPTX
4 character encoding-ascii
PPT
PDF
Process' Virtual Address Space in GNU/Linux
PPT
C scan scheduling 50 2
KEY
3장. Garbage Collection
PPTX
Paging-R.D.Sivakumar
PPT
Look scheduling.51
PPT
Sstf scheduling.50
PPT
Basic Garbage Collection Techniques
PPT
Fcfs scheduling
PPT
message passing
Java sockets
Present Continuous
Garbage Collection without Paging
Open and online: connections, community and reality
Copenhagen Open For Connections Dias
Multithreaded programming
Insert a Page Number in the Running Head
Presentiaon task sheduling first come first serve FCFS
The Look Of Love
4 character encoding-ascii
Process' Virtual Address Space in GNU/Linux
C scan scheduling 50 2
3장. Garbage Collection
Paging-R.D.Sivakumar
Look scheduling.51
Sstf scheduling.50
Basic Garbage Collection Techniques
Fcfs scheduling
message passing
Ad

Similar to Web sockets in Java (20)

PPTX
Enhancing Mobile User Experience with WebSocket
PDF
Lecture 6 Web Sockets
PDF
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
PDF
Getting Started with WebSockets and Server-Sent Events
PPT
JUG louvain websockets
PDF
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
PDF
Building Next Generation Real-Time Web Applications using Websockets
KEY
Websockets - DevFestX May 19, 2012
PPTX
vlavrynovych - WebSockets Presentation
PPTX
Websocket
PPTX
HTML 5 - Web Sockets
PPTX
Fight empire-html5
PDF
Getting Started with WebSocket and Server-Sent Events in Java
PPTX
Intro to Web Sockets
PDF
WebSocket
PDF
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
PDF
Speed up your Web applications with HTML5 WebSockets
PPT
PDF
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
PPTX
Programming WebSockets with Glassfish and Grizzly
Enhancing Mobile User Experience with WebSocket
Lecture 6 Web Sockets
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSockets and Server-Sent Events
JUG louvain websockets
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Building Next Generation Real-Time Web Applications using Websockets
Websockets - DevFestX May 19, 2012
vlavrynovych - WebSockets Presentation
Websocket
HTML 5 - Web Sockets
Fight empire-html5
Getting Started with WebSocket and Server-Sent Events in Java
Intro to Web Sockets
WebSocket
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Speed up your Web applications with HTML5 WebSockets
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Programming WebSockets with Glassfish and Grizzly

More from Pance Cavkovski (9)

PPTX
Jprofessionals co create the future of your city
PPTX
Gluing the IoT world with Java and LoRaWAN (Jfokus 2018)
PPTX
Gluing the iot world (ICT)
PPTX
Gluing the IoT world with Java and LoRaWAN
ODP
VDB16 - DIY Java & Kubernetes
ODP
DIY Java & Kubernetes
PPTX
Connected hardware for Software Engineers 101
PPTX
Hands on Java8 and RaspberryPi
PPTX
Micro and moblile: Java on the Raspberry Pi
Jprofessionals co create the future of your city
Gluing the IoT world with Java and LoRaWAN (Jfokus 2018)
Gluing the iot world (ICT)
Gluing the IoT world with Java and LoRaWAN
VDB16 - DIY Java & Kubernetes
DIY Java & Kubernetes
Connected hardware for Software Engineers 101
Hands on Java8 and RaspberryPi
Micro and moblile: Java on the Raspberry Pi

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Cloud computing and distributed systems.
PDF
Modernizing your data center with Dell and AMD
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
Encapsulation_ Review paper, used for researhc scholars
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25 Week I
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Cloud computing and distributed systems.
Modernizing your data center with Dell and AMD
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Network Security Unit 5.pdf for BCA BBA.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Building Integrated photovoltaic BIPV_UPV.pdf

Web sockets in Java

  • 1. WebSockets in Java From n00b to pro 22 Dec 2013, JavaDay, Pance Cavkovski
  • 2. Theory - WebSocket is a protocol providing full-duplex communications over a single TCP connection. - Standardized by IETF as RFC 6455 - Designed to be implemented in web browsers and web servers - HTTP Upgrade request for initiating connection * Contents from Wikipedia: http://en.wikipedia.org/wiki/Web_sockets GET /mychat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat Sec-WebSocket-Version: 13 Origin: http://example.com HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat Netcetera | 2
  • 4. public static void main(String[] args) JavaWebSocket (web-socket-samples/javawebsockets) public class Main extends WebSocketServer { public Main() { super(new InetSocketAddress(8887)); } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { //Handle new connection here conn.send(“{”connected”: true}”); } @Override public void onMessage(WebSocket conn, String message) { //Handle client received message here } * https://github.com/TooTallNate/Java-WebSocket @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { //Handle closing connection here } @Override public void onError(WebSocket conn, Exception exc) { //Handle error during transport here } public static void main(String[] args) { Main server = new Main(); server.start(); } } Netcetera | 4
  • 5. Client JavaScript WebSocket API var socket = new WebSocket(“ws://localhost:8887”); socket.onopen = function() { //event handler when the connection has been established socket.send(nickname); }; socket.onmessage = function(message) { //event handler when data has been received from the server alert(message.data); }; socket.onclose = function() { //event handler when the socket has been properly closed } socket.onerror = function() { //event handler when an error has occurred during communication } Netcetera | 5
  • 6. Java EE 7: JSR 356 + Java7 Tomcat (>7.0.43) (web-socket-samples/eesockets) @ServerEndpoint(“/chat”) public class EESocketChatEndpoint { @OnOpen public void onOpen(Session session) { //Handle new connection here session.getBasicRemote() .sendText(“{”connected”: true}”); } @OnMessage public void onMessage(String message) { //Handle client received message here } @OnClose public void onClose(Session session, CloseReason reason) { //Handle closing connection here } @OnError public void onError(Session session, Throwable throwable) { //Handle error during transport here } } * JSR 356, Java API for WebSocket: http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html (javax.websocket.*) Netcetera | 6
  • 7. Client Pretty much the same JavaScript WebSocket API var socket = new WebSocket(”ws://” + document.domain + “:8080/eesockets/chat”); socket.onopen = function() { //event handler when the connection has been established socket.send(nickname); }; socket.onmessage = function(message) { //event handler when data has been received from the server alert(message.data); }; socket.onclose = function() { //event handler when the socket has been properly closed } socket.onerror = function() { //event handler when an error has occurred during communication } Netcetera | 7
  • 8. Spring4 Static dispatcher servlet config public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{ @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{“/”}; } @Override protected void customizeRegistration(Dynamic registration) { registration.setInitParameter(“dispatchOptionsRequest”, “true”); } } Netcetera | 8
  • 9. Spring4 Static context config @Configuration @EnableWebMvc @EnableWebSocket @ComponentScan(basePackages={“mk.hsilomedus.springsockets.service”}) public class WebConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(chatWenSocketHandler(), “/chat”).withSockJS(); } @Bean public WebSocketHandler chatWebSocketHandler() { return new PerConnectionWebSocketHandler(ChatWebSocketHandler.class); } @Override public void configureDefaultServletHandling(DefaultServerHandlerConfigurer configurer) { configurer.enable(); } Netcetera | 9 }
  • 10. Spring4 WebSocketHandler (web-socket-samples/springsockets) public class ChatWebSocketHandler extends TextWebSocketHandler { @Override public void afterConnectionEstablished( WebSocketSession session) { //Handle new connection here session.sendMessage( “{”connected”: true}”); } @Override public void handleTextMessage( WebSocketSession session, TextMessage message) { //Handle message.getPayload() here } * http://blog.gopivotal.com/products/websocket-architecture-in-spring-4-0 @Override public void afterConnectionClosed( WebSocketSession session, CloseStatus status) { //Handle closing connection here } @Override public void handleTransportError( WebSocketSession session, Throwable exception) { //Handle error during transport here } } Netcetera | 10
  • 11. Client SockJS //I can now fallback to longpoll and do IE9!!! var socket = new SockJS(”http://” + document.domain + “:8080/springsockets/chat”); socket.onopen = function() { //event handler when the connection has been established socket.send(nickname); }; socket.onmessage = function(message) { //event handler when data has been received from the server alert(message.data); }; socket.onclose = function() { //event handler when the socket has been properly closed } socket.onerror = function() { //event handler when an error has occurred during communication } Netcetera | 11
  • 12. socket.close(); Thanks for your attention - The whole source code is available on github: https://github.com/hsilomedus/web-sockets-samples - /javawebsockets – with the JavaWebSocket library - /eesockets – with Tomcat 7.0.47 - /springsockets – with Spring4 RC2 and Tomcat 7.0.47 - All three are eclipse projects running on Java7 - Questions? - https://twitter.com/hsilomedus, http://hsilomedus.me/ Netcetera | 12