SlideShare a Scribd company logo
1 of 12
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

What's hot

Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalable
Gareth Marland
 

What's hot (20)

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
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Php push notifications
Php push notificationsPhp push notifications
Php push notifications
 
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
 
Intro to WebSockets
Intro to WebSocketsIntro to WebSockets
Intro to WebSockets
 
Websocket protocol overview
Websocket protocol overviewWebsocket protocol overview
Websocket protocol overview
 
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!
 
Reverse ajax in 2014
Reverse ajax in 2014Reverse ajax in 2014
Reverse ajax in 2014
 
Ws
WsWs
Ws
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
J web socket
J web socketJ web socket
J web socket
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Framework
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !
 
Large scale web socket system with AWS and Web socket
Large scale web socket system with AWS and Web socketLarge scale web socket system with AWS and Web socket
Large scale web socket system with AWS and Web socket
 
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and ScalaWriting highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
 
Building WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using AtmosphereBuilding WebSocket and Server Side Events Applications using Atmosphere
Building WebSocket and Server Side Events Applications using Atmosphere
 
Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalable
 

Viewers also liked

Copenhagen Open For Connections Dias
Copenhagen Open For Connections DiasCopenhagen Open For Connections Dias
Copenhagen Open For Connections Dias
Wonderful Copenhagen
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Presentiaon task sheduling first come first serve FCFS
Presentiaon  task sheduling first come first serve FCFSPresentiaon  task sheduling first come first serve FCFS
Presentiaon task sheduling first come first serve FCFS
Ahmed Salah
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
irdginfo
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
Varun Mahajan
 
C scan scheduling 50 2
C scan scheduling 50 2C scan scheduling 50 2
C scan scheduling 50 2
myrajendra
 
Look scheduling.51
Look scheduling.51Look scheduling.51
Look scheduling.51
myrajendra
 
Sstf scheduling.50
Sstf scheduling.50Sstf scheduling.50
Sstf scheduling.50
myrajendra
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
An Khuong
 
Fcfs scheduling
Fcfs schedulingFcfs scheduling
Fcfs scheduling
myrajendra
 

Viewers also liked (20)

Java sockets
Java socketsJava sockets
Java sockets
 
Present Continuous
Present ContinuousPresent Continuous
Present Continuous
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without Paging
 
Open and online: connections, community and reality
Open and online: connections, community and reality Open and online: connections, community and reality
Open and online: connections, community and reality
 
Copenhagen Open For Connections Dias
Copenhagen Open For Connections DiasCopenhagen Open For Connections Dias
Copenhagen Open For Connections Dias
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Insert a Page Number in the Running Head
Insert a Page Number in the Running HeadInsert a Page Number in the Running Head
Insert a Page Number in the Running Head
 
Presentiaon task sheduling first come first serve FCFS
Presentiaon  task sheduling first come first serve FCFSPresentiaon  task sheduling first come first serve FCFS
Presentiaon task sheduling first come first serve FCFS
 
The Look Of Love
The Look Of LoveThe Look Of Love
The Look Of Love
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
 
Ascii codes
Ascii codesAscii codes
Ascii codes
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
 
C scan scheduling 50 2
C scan scheduling 50 2C scan scheduling 50 2
C scan scheduling 50 2
 
3장. Garbage Collection
3장. Garbage Collection3장. Garbage Collection
3장. Garbage Collection
 
Paging-R.D.Sivakumar
Paging-R.D.SivakumarPaging-R.D.Sivakumar
Paging-R.D.Sivakumar
 
Look scheduling.51
Look scheduling.51Look scheduling.51
Look scheduling.51
 
Sstf scheduling.50
Sstf scheduling.50Sstf scheduling.50
Sstf scheduling.50
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
 
Fcfs scheduling
Fcfs schedulingFcfs scheduling
Fcfs scheduling
 
message passing
 message passing message passing
message passing
 

Similar to Web sockets in Java

Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
jobandesther
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
Sameer Segal
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
lonegunman
 

Similar to Web sockets in Java (20)

Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & Deitel
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile Devices
 
Servlets
ServletsServlets
Servlets
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Html5 websockets
Html5 websocketsHtml5 websockets
Html5 websockets
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
React Native EU 2021 - Creating a VoIP app in React Native - the beginner's g...
React Native EU 2021 - Creating a VoIP app in React Native - the beginner's g...React Native EU 2021 - Creating a VoIP app in React Native - the beginner's g...
React Native EU 2021 - Creating a VoIP app in React Native - the beginner's g...
 
Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking features
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCL
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practice
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 

More from Pance Cavkovski (9)

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

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 

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