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

Building Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsBuilding Real-Time Applications with Android and WebSockets
Building Real-Time Applications with Android and WebSocketsSergi Almar i Graupera
 
HTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebHTML5 WebSocket: The New Network Stack for the Web
HTML5 WebSocket: The New Network Stack for the WebPeter Lubbers
 
Websocket protocol overview
Websocket protocol overviewWebsocket protocol overview
Websocket protocol overviewallenmeng
 
Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!Websockets on the JVM: Atmosphere to the rescue!
Websockets on the JVM: Atmosphere to the rescue!jfarcand
 
Reverse ajax in 2014
Reverse ajax in 2014Reverse ajax in 2014
Reverse ajax in 2014Nenad Pecanac
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!Andrew Conner
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Frameworkjfarcand
 
Using Websockets in Play !
Using Websockets in Play !Using Websockets in Play !
Using Websockets in Play !Knoldus Inc.
 
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 socketLe Kien Truc
 
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 Scalajfarcand
 
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 Atmospherejfarcand
 
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 scalableGareth 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

Present Continuous
Present ContinuousPresent Continuous
Present Continuouslupitath09
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without PagingEmery Berger
 
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 Catherine Cronin
 
Copenhagen Open For Connections Dias
Copenhagen Open For Connections DiasCopenhagen Open For Connections Dias
Copenhagen Open For Connections DiasWonderful Copenhagen
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programmingSonam Sharma
 
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 HeadAmy Lynn Hess
 
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 FCFSAhmed Salah
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-asciiirdginfo
 
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/LinuxVarun Mahajan
 
C scan scheduling 50 2
C scan scheduling 50 2C scan scheduling 50 2
C scan scheduling 50 2myrajendra
 
3장. Garbage Collection
3장. Garbage Collection3장. Garbage Collection
3장. Garbage Collection김 한도
 
Look scheduling.51
Look scheduling.51Look scheduling.51
Look scheduling.51myrajendra
 
Sstf scheduling.50
Sstf scheduling.50Sstf scheduling.50
Sstf scheduling.50myrajendra
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection TechniquesAn Khuong
 
Fcfs scheduling
Fcfs schedulingFcfs scheduling
Fcfs schedulingmyrajendra
 

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 WebSocket in Java Guide From Novice to Pro

Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Chapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelChapter 27 Networking - Deitel & Deitel
Chapter 27 Networking - Deitel & DeitelCSDeptSriKaliswariCo
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
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 2020Matt Raible
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Sameer Segal
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesMaksym Davydov
 
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 SessionDavid Gómez García
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3JavaEE Trainers
 
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...Wojciech Kwiatek
 
Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking featuresstrikr .
 
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 WebSocketsYakov Fain
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCLFastly
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservicelonegunman
 

Similar to WebSocket in Java Guide From Novice to Pro (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

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 cityPance Cavkovski
 
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)Pance Cavkovski
 
Gluing the iot world (ICT)
Gluing the iot world (ICT)Gluing the iot world (ICT)
Gluing the iot world (ICT)Pance Cavkovski
 
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 LoRaWANPance Cavkovski
 
VDB16 - DIY Java & Kubernetes
VDB16 - DIY Java & KubernetesVDB16 - DIY Java & Kubernetes
VDB16 - DIY Java & KubernetesPance Cavkovski
 
Connected hardware for Software Engineers 101
Connected hardware for Software Engineers 101Connected hardware for Software Engineers 101
Connected hardware for Software Engineers 101Pance Cavkovski
 
Hands on Java8 and RaspberryPi
Hands on Java8 and RaspberryPiHands on Java8 and RaspberryPi
Hands on Java8 and RaspberryPiPance Cavkovski
 
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 PiPance Cavkovski
 

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

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

WebSocket in Java Guide From Novice to Pro

  • 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