SlideShare a Scribd company logo
WebSockets in
Play! Framework
Fabio Tiriticco
@ticofab
Scala Academy
20 March 2014
Amsterdam Scala
Two words about myself
Currently freelancing and working on my own ideas.
…one of which involves and WebSockets!
Bicycle Touring Amsterdam
Agenda
• What are WebSockets?
• WebSocket clients
• Relationship and comparison with HTTP
• Advantages and disadvantages
• WebSocket servers in Play!
• Simple examples & exercises
• Use case
What are WebSockets?
• Full-duplex channel between client and server.
• Persistent connection. Both parties can send data
at any time.
• Very simple API.
• Standardised by the IETF as RFC 6455 in 2011,
which has lead to broader adoption.
The TCP / IP stack
WEBSOCKET
The API, Client-side
RECEPTION CALLBACKS
• onOpen
• onClosed
• onMessage(message)
• onError(error)
CONNECTION
• open
• close
SEND DATA
• send(message)
var myWebSocket = new WebSocket("ws://fabio.com/example");
// define callbacks
myWebSocket.onmessage = function(event) {
console.log("got data: " + event.data);
}
myWebSocket.onopen = function(event) {
console.log("Connection open ...");
};
myWebSocket.onclose = function(event) {
console.log("Connection closed.");
};
myWebSocket.onerror = function(event) {
console.log("Error!");
};
myWebSocket.send("Hello from Javascript!”); // send stuff
myWebSocket.close(); // close connection
JavaScript client example
WebSocketClient mWsClient = new WebSocketClient(URI.create(“ws://fabio.com/example”), new
Listener() {
@Override
public void onMessage(final String message) {
Log.d(TAG, “onMessage: ” + message);
}
@Override
public void onError(final Exception error) {
Log.e(TAG, "Error!", error);
}
@Override
public void onDisconnect(final int code, final String reason) {
Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
}
@Override
public void onConnect() {
Log.d(TAG, "onConnect");
}
}, mExtraHeaders);
mWsClient.connect();
mWsClient.send(“Hello from Android!”);
mWSClient.disconnect();
Android (Java) client example
Request URL:ws://echo.websocket.org/
Request Method:GET
Status Code:101 Web Socket Protocol Handshake
Connection:Upgrade
Host:echo.websocket.org
Sec-WebSocket-Version:13
Upgrade:websocket
Relationship with HTTP
• A websocket connection is initiated via a
standard HTTP GET request, where the client
asks for an ‘Upgrade’
• The response will be a 101 status, ‘Switching
protocol’
Why WebSockets?
• The ‘native’ web built around HTTP only relies on
client’s action. Only the client can request new content
by for instance opening a new page.
• A way to make things more dynamic is using intense
polling, which is bad for performance and traffic.
• The need to give impression of a ‘dynamic’ web was
solved using workarounds like Long-polling or
Streaming.
• It works but it’s complicated and it doesn’t solve the
big issue of the HTTP overhead!
WS vs HTTP: overhead
HTTP: up to 2000 bytes (2Kb)
WebSocket: 2 bytes
WS vs HTTP: processing time
Downsides of WebSockets
• You need to build your own protocol, even for the
simplest thing! You cannot use any of the friendly
HTTP statuses, body etc. Lower level of abstraction.
• If your application doesn’t require a lot of dynamic
interaction, HTTP is much simpler to implement.
• Regular sockets vs WebSockets: plain TCP is even
faster, but very low level (difficult to access).
A few useful links
• https://tools.ietf.org/html/rfc6455 (official doc)
• http://www.html5rocks.com/en/tutorials/websockets/
basics/ (basic tutorial)
• http://www.websocket.org (the echo server folks)
• http://blog.arungupta.me/2014/02/rest-vs-websocket-
comparison-benchmarks/ (HTTP vs WebSocket
comparison)
• http://eng.42go.com/websockets-vs-regular-sockets/
WebSockets in Play!
Similar signature to a regular HTTP Action:
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
def index = WebSocket.using[String] { request =>
val in = Iteratee.foreach[String](chunk => println(chunk))
val out = Enumerator("Hello!")
(in, out)
}
using[A](f: (RequestHeader) (Iteratee[A, _], Enumerator[A]))
WebSocket.using signature:
WebSockets in Play!
There is also an ‘async’ version which combines the
two channels asynchronously and returns a Future.
def index = WebSocket.async[String] { request =>
Future {
val in = Iteratee.foreach[String](chunk => println(chunk))
val out = Enumerator("Hello!")
(in, out)
}
}
async[A](f: (RequestHeader) Future[(Iteratee[A, _], Enumerator[A])])
WebSocket.async signature:
Iteratees and Enumerators
• Complex functional abstractions. Very powerful but
difficult to grasp.
• In the WebSocket domain, all you need to know is that
they represent the two channels where data flows
between client and server.
Iteratees & Enumerators
How To
• They both take a type:
• Play! Framework provides various utilities to create
them and use them together.
• Time for some concrete examples!
trait Iteratee[E, +A] extends AnyRef
trait Enumerator[E] extends AnyRef
Repositories
(ask Google for “ticofab github” or something like that)
• https://github.com/ticofab/simple-websocket-client
(test client)
• https://github.com/ticofab/simple-play-websocket-
server (test server)
WebSockets in Play!
Even though you can wrap the pair (Iteratee, Enumerator) into
an Actor, the framework also offers a way to manage a
WebSocket using actors out of the box. The signature of the
accept function is unusual: a function that returns a function
which takes an ActorRef and returns the Props of an actor!
acceptWithActor[A, B](f: (RequestHeader) (ActorRef) Props)
There is also a way to reject a Websocket connection:
tryAcceptWithActor[A, B](f: (RequestHeader) Future[Either[Result,
(ActorRef) Props]])
Return Left to reject or Right(WebsocketActor.Props) to accept.
def index = WebSocket.acceptWithActor[String, String] { request => out =>
WebsocketActor.props(out)
}
object MyWebSocketActor {
def props(out: ActorRef) = Props(new WebsocketActor(out))
}
class WebsocketActor(out: ActorRef) extends Actor {
def receive = {
case msg: String =>
out ! ("I received your message: " + msg)
}
}
WebSockets in Play!
Little exercise
1. Uses Actors to handle connections wrapping Iteratee and
Enumerators.
2. It echoes anything it receives, but closes the connection if it
receives a specific string of your choice.
3. Bonus: make the endpoint proxy the result of the API call to:
Create a new Play! app with a WebSocket endpoint.
http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,nl
Two good articles
• Iteratees and Enumerators for human beings: http://
mandubian.com/2012/08/27/understanding-play2-
iteratees-for-normal-humans/
• WebSocket examples: http://blog.tksfz.org/
2012/10/12/websockets-echo-using-play-scala-
and-actors-part-i/
Use case
Play! Framework sample:
WebSocket chat
Thank you
Websocket in Play!Framework
@ticofab

More Related Content

What's hot

OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
Leonardo Nve Egea
 
Fluent Bit: Log Forwarding at Scale
Fluent Bit: Log Forwarding at ScaleFluent Bit: Log Forwarding at Scale
Fluent Bit: Log Forwarding at Scale
Eduardo Silva Pereira
 
Vpn
VpnVpn
Vpn
kwabo
 
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
SmartnSkilled
 
Network LACP/Bonding/Teaming with Mikrotik
Network LACP/Bonding/Teaming with MikrotikNetwork LACP/Bonding/Teaming with Mikrotik
Network LACP/Bonding/Teaming with Mikrotik
GLC Networks
 
Graylog for open stack 3 steps to know why
Graylog for open stack    3 steps to know whyGraylog for open stack    3 steps to know why
Graylog for open stack 3 steps to know why
Vietnam Open Infrastructure User Group
 
Cours - Supervision SysRes et Présentation de Nagios
Cours - Supervision SysRes et Présentation de NagiosCours - Supervision SysRes et Présentation de Nagios
Cours - Supervision SysRes et Présentation de Nagios
Erwan 'Labynocle' Ben Souiden
 
Tuto VP IPSEC Site-to-site
Tuto VP IPSEC Site-to-siteTuto VP IPSEC Site-to-site
Tuto VP IPSEC Site-to-site
Dimitri LEMBOKOLO
 
Installation de snort avec pulled pork
Installation de snort avec pulled porkInstallation de snort avec pulled pork
Installation de snort avec pulled pork
SamiMessaoudi4
 
A Distributed Malware Analysis System Cuckoo Sandbox
A Distributed Malware Analysis System Cuckoo SandboxA Distributed Malware Analysis System Cuckoo Sandbox
A Distributed Malware Analysis System Cuckoo Sandbox
Andy Lee
 
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOSPart 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
Men and Mice
 
Hypervisors Vs Bare Metal Servers: a Beginner’s Guide
Hypervisors Vs Bare Metal Servers: a Beginner’s GuideHypervisors Vs Bare Metal Servers: a Beginner’s Guide
Hypervisors Vs Bare Metal Servers: a Beginner’s Guide
GlobalTeleHost Corp.
 
501 ch-1-mastering-security-basics
501 ch-1-mastering-security-basics501 ch-1-mastering-security-basics
501 ch-1-mastering-security-basics
gocybersec
 
Supervision V2 ppt
Supervision V2 pptSupervision V2 ppt
Supervision V2 pptjeehane
 
Introduction to MPI
Introduction to MPI Introduction to MPI
Introduction to MPI
Hanif Durad
 
Security Onion - Introduction
Security Onion - IntroductionSecurity Onion - Introduction
Security Onion - Introduction
n|u - The Open Security Community
 
Security Automation and Orchestration
Security Automation and OrchestrationSecurity Automation and Orchestration
Security Automation and Orchestration
Greg Foss
 
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSMDéveloppement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
Mohamed Raafat OMRI محمد رأفت عمري
 

What's hot (20)

OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
 
Fluent Bit: Log Forwarding at Scale
Fluent Bit: Log Forwarding at ScaleFluent Bit: Log Forwarding at Scale
Fluent Bit: Log Forwarding at Scale
 
Vpn
VpnVpn
Vpn
 
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
Support formation vidéo : Réussir la certification Linux LPIC-1 (1)
 
Network LACP/Bonding/Teaming with Mikrotik
Network LACP/Bonding/Teaming with MikrotikNetwork LACP/Bonding/Teaming with Mikrotik
Network LACP/Bonding/Teaming with Mikrotik
 
Graylog for open stack 3 steps to know why
Graylog for open stack    3 steps to know whyGraylog for open stack    3 steps to know why
Graylog for open stack 3 steps to know why
 
Cours - Supervision SysRes et Présentation de Nagios
Cours - Supervision SysRes et Présentation de NagiosCours - Supervision SysRes et Présentation de Nagios
Cours - Supervision SysRes et Présentation de Nagios
 
Tuto VP IPSEC Site-to-site
Tuto VP IPSEC Site-to-siteTuto VP IPSEC Site-to-site
Tuto VP IPSEC Site-to-site
 
Installation de snort avec pulled pork
Installation de snort avec pulled porkInstallation de snort avec pulled pork
Installation de snort avec pulled pork
 
A Distributed Malware Analysis System Cuckoo Sandbox
A Distributed Malware Analysis System Cuckoo SandboxA Distributed Malware Analysis System Cuckoo Sandbox
A Distributed Malware Analysis System Cuckoo Sandbox
 
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOSPart 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
Part 3 - Local Name Resolution in Linux, FreeBSD and macOS/iOS
 
Tomcatx performance-tuning
Tomcatx performance-tuningTomcatx performance-tuning
Tomcatx performance-tuning
 
Hypervisors Vs Bare Metal Servers: a Beginner’s Guide
Hypervisors Vs Bare Metal Servers: a Beginner’s GuideHypervisors Vs Bare Metal Servers: a Beginner’s Guide
Hypervisors Vs Bare Metal Servers: a Beginner’s Guide
 
501 ch-1-mastering-security-basics
501 ch-1-mastering-security-basics501 ch-1-mastering-security-basics
501 ch-1-mastering-security-basics
 
Supervision V2 ppt
Supervision V2 pptSupervision V2 ppt
Supervision V2 ppt
 
Vpn
VpnVpn
Vpn
 
Introduction to MPI
Introduction to MPI Introduction to MPI
Introduction to MPI
 
Security Onion - Introduction
Security Onion - IntroductionSecurity Onion - Introduction
Security Onion - Introduction
 
Security Automation and Orchestration
Security Automation and OrchestrationSecurity Automation and Orchestration
Security Automation and Orchestration
 
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSMDéveloppement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
Développement d’un Outil d’Aide À la Planification du Réseau Coeur GSM
 

Viewers also liked

Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
Andrew Conner
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 
Reactive in Android and Beyond Rx
Reactive in Android and Beyond RxReactive in Android and Beyond Rx
Reactive in Android and Beyond Rx
Fabio Tiriticco
 
API Design and WebSocket
API Design and WebSocketAPI Design and WebSocket
API Design and WebSocket
Frank Greco
 
WebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST MicroserviceWebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST Microservice
Rick Hightower
 
Training Webinar: Enterprise application performance with server push technol...
Training Webinar: Enterprise application performance with server push technol...Training Webinar: Enterprise application performance with server push technol...
Training Webinar: Enterprise application performance with server push technol...
OutSystems
 
Developing an Akka Edge4-5
Developing an Akka Edge4-5Developing an Akka Edge4-5
Developing an Akka Edge4-5
saaaaaaki
 
Why Play Framework is fast
Why Play Framework is fastWhy Play Framework is fast
Why Play Framework is fast
Legacy Typesafe (now Lightbend)
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
Stephen Chin
 

Viewers also liked (9)

Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Reactive in Android and Beyond Rx
Reactive in Android and Beyond RxReactive in Android and Beyond Rx
Reactive in Android and Beyond Rx
 
API Design and WebSocket
API Design and WebSocketAPI Design and WebSocket
API Design and WebSocket
 
WebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST MicroserviceWebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST Microservice
 
Training Webinar: Enterprise application performance with server push technol...
Training Webinar: Enterprise application performance with server push technol...Training Webinar: Enterprise application performance with server push technol...
Training Webinar: Enterprise application performance with server push technol...
 
Developing an Akka Edge4-5
Developing an Akka Edge4-5Developing an Akka Edge4-5
Developing an Akka Edge4-5
 
Why Play Framework is fast
Why Play Framework is fastWhy Play Framework is fast
Why Play Framework is fast
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
 

Similar to WebSockets wiith Scala and Play! Framework

Web-Socket
Web-SocketWeb-Socket
Web sockets - Pentesting
Web sockets - Pentesting Web sockets - Pentesting
Web sockets - Pentesting
Vandana Verma
 
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
Edward Burns
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
pkaviya
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
Sepehr Rasouli
 
Tools. Techniques. Trouble?
Tools. Techniques. Trouble?Tools. Techniques. Trouble?
Tools. Techniques. Trouble?
Testplant
 
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Html5 web sockets - Brad Drysdale - London Web 2011-10-20Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Nathan O'Hanlon
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
Fahad Golra
 
How to Build Single Page HTML5 Apps that Scale
How to Build Single Page HTML5 Apps that ScaleHow to Build Single Page HTML5 Apps that Scale
How to Build Single Page HTML5 Apps that Scale
Phil Leggetter
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
David Lindkvist
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
Brian Huff
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
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
Peter Lubbers
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
ramya marichamy
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
Henry S
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
Kevin Hazzard
 
BEST REST in OpenStack
BEST REST in OpenStackBEST REST in OpenStack
BEST REST in OpenStack
Vikram G Hosakote
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossugclkao
 

Similar to WebSockets wiith Scala and Play! Framework (20)

Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Web sockets - Pentesting
Web sockets - Pentesting Web sockets - Pentesting
Web sockets - Pentesting
 
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
 
Tools. Techniques. Trouble?
Tools. Techniques. Trouble?Tools. Techniques. Trouble?
Tools. Techniques. Trouble?
 
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Html5 web sockets - Brad Drysdale - London Web 2011-10-20Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
How to Build Single Page HTML5 Apps that Scale
How to Build Single Page HTML5 Apps that ScaleHow to Build Single Page HTML5 Apps that Scale
How to Build Single Page HTML5 Apps that Scale
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
 
Intro to WebSockets
Intro to WebSocketsIntro to WebSockets
Intro to WebSockets
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
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
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
BEST REST in OpenStack
BEST REST in OpenStackBEST REST in OpenStack
BEST REST in OpenStack
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
 

More from Fabio Tiriticco

Intro slides - Global Reactive Meetup - Move over JDBC!
Intro slides - Global Reactive Meetup - Move over JDBC!Intro slides - Global Reactive Meetup - Move over JDBC!
Intro slides - Global Reactive Meetup - Move over JDBC!
Fabio Tiriticco
 
Planespotting - From Zero To Deep Learning
Planespotting - From Zero To Deep Learning Planespotting - From Zero To Deep Learning
Planespotting - From Zero To Deep Learning
Fabio Tiriticco
 
From Zero To Deep Learning With Scala
From Zero To Deep Learning With ScalaFrom Zero To Deep Learning With Scala
From Zero To Deep Learning With Scala
Fabio Tiriticco
 
Reactive Amsterdam - Maxim Burgerhout - Quarkus Intro
Reactive Amsterdam - Maxim Burgerhout - Quarkus IntroReactive Amsterdam - Maxim Burgerhout - Quarkus Intro
Reactive Amsterdam - Maxim Burgerhout - Quarkus Intro
Fabio Tiriticco
 
Ten Frustrations From The Community Trenches (And How To Deal With Them)
Ten Frustrations From The Community Trenches (And How To Deal With Them)Ten Frustrations From The Community Trenches (And How To Deal With Them)
Ten Frustrations From The Community Trenches (And How To Deal With Them)
Fabio Tiriticco
 
We all need friends and Akka just found Kubernetes
We all need friends and Akka just found KubernetesWe all need friends and Akka just found Kubernetes
We all need friends and Akka just found Kubernetes
Fabio Tiriticco
 
Cloud native akka and kubernetes holy grail to elasticity
Cloud native akka and kubernetes   holy grail to elasticityCloud native akka and kubernetes   holy grail to elasticity
Cloud native akka and kubernetes holy grail to elasticity
Fabio Tiriticco
 
Reactive Summit 2017 Highlights!
Reactive Summit 2017 Highlights!Reactive Summit 2017 Highlights!
Reactive Summit 2017 Highlights!
Fabio Tiriticco
 
Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)
Fabio Tiriticco
 
Beyond Fault Tolerance with Actor Programming
Beyond Fault Tolerance with Actor ProgrammingBeyond Fault Tolerance with Actor Programming
Beyond Fault Tolerance with Actor Programming
Fabio Tiriticco
 
Akka Streams at Weeronline
Akka Streams at WeeronlineAkka Streams at Weeronline
Akka Streams at Weeronline
Fabio Tiriticco
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
Fabio Tiriticco
 

More from Fabio Tiriticco (12)

Intro slides - Global Reactive Meetup - Move over JDBC!
Intro slides - Global Reactive Meetup - Move over JDBC!Intro slides - Global Reactive Meetup - Move over JDBC!
Intro slides - Global Reactive Meetup - Move over JDBC!
 
Planespotting - From Zero To Deep Learning
Planespotting - From Zero To Deep Learning Planespotting - From Zero To Deep Learning
Planespotting - From Zero To Deep Learning
 
From Zero To Deep Learning With Scala
From Zero To Deep Learning With ScalaFrom Zero To Deep Learning With Scala
From Zero To Deep Learning With Scala
 
Reactive Amsterdam - Maxim Burgerhout - Quarkus Intro
Reactive Amsterdam - Maxim Burgerhout - Quarkus IntroReactive Amsterdam - Maxim Burgerhout - Quarkus Intro
Reactive Amsterdam - Maxim Burgerhout - Quarkus Intro
 
Ten Frustrations From The Community Trenches (And How To Deal With Them)
Ten Frustrations From The Community Trenches (And How To Deal With Them)Ten Frustrations From The Community Trenches (And How To Deal With Them)
Ten Frustrations From The Community Trenches (And How To Deal With Them)
 
We all need friends and Akka just found Kubernetes
We all need friends and Akka just found KubernetesWe all need friends and Akka just found Kubernetes
We all need friends and Akka just found Kubernetes
 
Cloud native akka and kubernetes holy grail to elasticity
Cloud native akka and kubernetes   holy grail to elasticityCloud native akka and kubernetes   holy grail to elasticity
Cloud native akka and kubernetes holy grail to elasticity
 
Reactive Summit 2017 Highlights!
Reactive Summit 2017 Highlights!Reactive Summit 2017 Highlights!
Reactive Summit 2017 Highlights!
 
Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)Reactive Programming or Reactive Systems? (spoiler: both)
Reactive Programming or Reactive Systems? (spoiler: both)
 
Beyond Fault Tolerance with Actor Programming
Beyond Fault Tolerance with Actor ProgrammingBeyond Fault Tolerance with Actor Programming
Beyond Fault Tolerance with Actor Programming
 
Akka Streams at Weeronline
Akka Streams at WeeronlineAkka Streams at Weeronline
Akka Streams at Weeronline
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 

WebSockets wiith Scala and Play! Framework

  • 1. WebSockets in Play! Framework Fabio Tiriticco @ticofab Scala Academy 20 March 2014 Amsterdam Scala
  • 2. Two words about myself Currently freelancing and working on my own ideas. …one of which involves and WebSockets! Bicycle Touring Amsterdam
  • 3. Agenda • What are WebSockets? • WebSocket clients • Relationship and comparison with HTTP • Advantages and disadvantages • WebSocket servers in Play! • Simple examples & exercises • Use case
  • 4. What are WebSockets? • Full-duplex channel between client and server. • Persistent connection. Both parties can send data at any time. • Very simple API. • Standardised by the IETF as RFC 6455 in 2011, which has lead to broader adoption.
  • 5. The TCP / IP stack WEBSOCKET
  • 6. The API, Client-side RECEPTION CALLBACKS • onOpen • onClosed • onMessage(message) • onError(error) CONNECTION • open • close SEND DATA • send(message)
  • 7. var myWebSocket = new WebSocket("ws://fabio.com/example"); // define callbacks myWebSocket.onmessage = function(event) { console.log("got data: " + event.data); } myWebSocket.onopen = function(event) { console.log("Connection open ..."); }; myWebSocket.onclose = function(event) { console.log("Connection closed."); }; myWebSocket.onerror = function(event) { console.log("Error!"); }; myWebSocket.send("Hello from Javascript!”); // send stuff myWebSocket.close(); // close connection JavaScript client example
  • 8. WebSocketClient mWsClient = new WebSocketClient(URI.create(“ws://fabio.com/example”), new Listener() { @Override public void onMessage(final String message) { Log.d(TAG, “onMessage: ” + message); } @Override public void onError(final Exception error) { Log.e(TAG, "Error!", error); } @Override public void onDisconnect(final int code, final String reason) { Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason)); } @Override public void onConnect() { Log.d(TAG, "onConnect"); } }, mExtraHeaders); mWsClient.connect(); mWsClient.send(“Hello from Android!”); mWSClient.disconnect(); Android (Java) client example
  • 9. Request URL:ws://echo.websocket.org/ Request Method:GET Status Code:101 Web Socket Protocol Handshake Connection:Upgrade Host:echo.websocket.org Sec-WebSocket-Version:13 Upgrade:websocket Relationship with HTTP • A websocket connection is initiated via a standard HTTP GET request, where the client asks for an ‘Upgrade’ • The response will be a 101 status, ‘Switching protocol’
  • 10. Why WebSockets? • The ‘native’ web built around HTTP only relies on client’s action. Only the client can request new content by for instance opening a new page. • A way to make things more dynamic is using intense polling, which is bad for performance and traffic. • The need to give impression of a ‘dynamic’ web was solved using workarounds like Long-polling or Streaming. • It works but it’s complicated and it doesn’t solve the big issue of the HTTP overhead!
  • 11. WS vs HTTP: overhead HTTP: up to 2000 bytes (2Kb) WebSocket: 2 bytes
  • 12. WS vs HTTP: processing time
  • 13. Downsides of WebSockets • You need to build your own protocol, even for the simplest thing! You cannot use any of the friendly HTTP statuses, body etc. Lower level of abstraction. • If your application doesn’t require a lot of dynamic interaction, HTTP is much simpler to implement. • Regular sockets vs WebSockets: plain TCP is even faster, but very low level (difficult to access).
  • 14. A few useful links • https://tools.ietf.org/html/rfc6455 (official doc) • http://www.html5rocks.com/en/tutorials/websockets/ basics/ (basic tutorial) • http://www.websocket.org (the echo server folks) • http://blog.arungupta.me/2014/02/rest-vs-websocket- comparison-benchmarks/ (HTTP vs WebSocket comparison) • http://eng.42go.com/websockets-vs-regular-sockets/
  • 15. WebSockets in Play! Similar signature to a regular HTTP Action: val echo = Action { request => Ok("Got request [" + request + "]") } def index = WebSocket.using[String] { request => val in = Iteratee.foreach[String](chunk => println(chunk)) val out = Enumerator("Hello!") (in, out) } using[A](f: (RequestHeader) (Iteratee[A, _], Enumerator[A])) WebSocket.using signature:
  • 16. WebSockets in Play! There is also an ‘async’ version which combines the two channels asynchronously and returns a Future. def index = WebSocket.async[String] { request => Future { val in = Iteratee.foreach[String](chunk => println(chunk)) val out = Enumerator("Hello!") (in, out) } } async[A](f: (RequestHeader) Future[(Iteratee[A, _], Enumerator[A])]) WebSocket.async signature:
  • 17. Iteratees and Enumerators • Complex functional abstractions. Very powerful but difficult to grasp. • In the WebSocket domain, all you need to know is that they represent the two channels where data flows between client and server.
  • 18. Iteratees & Enumerators How To • They both take a type: • Play! Framework provides various utilities to create them and use them together. • Time for some concrete examples! trait Iteratee[E, +A] extends AnyRef trait Enumerator[E] extends AnyRef
  • 19. Repositories (ask Google for “ticofab github” or something like that) • https://github.com/ticofab/simple-websocket-client (test client) • https://github.com/ticofab/simple-play-websocket- server (test server)
  • 20. WebSockets in Play! Even though you can wrap the pair (Iteratee, Enumerator) into an Actor, the framework also offers a way to manage a WebSocket using actors out of the box. The signature of the accept function is unusual: a function that returns a function which takes an ActorRef and returns the Props of an actor! acceptWithActor[A, B](f: (RequestHeader) (ActorRef) Props) There is also a way to reject a Websocket connection: tryAcceptWithActor[A, B](f: (RequestHeader) Future[Either[Result, (ActorRef) Props]]) Return Left to reject or Right(WebsocketActor.Props) to accept.
  • 21. def index = WebSocket.acceptWithActor[String, String] { request => out => WebsocketActor.props(out) } object MyWebSocketActor { def props(out: ActorRef) = Props(new WebsocketActor(out)) } class WebsocketActor(out: ActorRef) extends Actor { def receive = { case msg: String => out ! ("I received your message: " + msg) } } WebSockets in Play!
  • 22. Little exercise 1. Uses Actors to handle connections wrapping Iteratee and Enumerators. 2. It echoes anything it receives, but closes the connection if it receives a specific string of your choice. 3. Bonus: make the endpoint proxy the result of the API call to: Create a new Play! app with a WebSocket endpoint. http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,nl
  • 23. Two good articles • Iteratees and Enumerators for human beings: http:// mandubian.com/2012/08/27/understanding-play2- iteratees-for-normal-humans/ • WebSocket examples: http://blog.tksfz.org/ 2012/10/12/websockets-echo-using-play-scala- and-actors-part-i/
  • 24. Use case Play! Framework sample: WebSocket chat
  • 25. Thank you Websocket in Play!Framework @ticofab