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

PDF
LLVM Register Allocation (2nd Version)
PPTX
Debugging Modern C++ Application with Gdb
PPSX
OOP with Java - Part 3
PPTX
U-Boot Porting on New Hardware
PDF
Python avancé : Ensemble, dictionnaire et base de données
PDF
OFI libfabric Tutorial
PDF
Programmation en C
PDF
Tp1 - Initiation à Java-Eclipse
LLVM Register Allocation (2nd Version)
Debugging Modern C++ Application with Gdb
OOP with Java - Part 3
U-Boot Porting on New Hardware
Python avancé : Ensemble, dictionnaire et base de données
OFI libfabric Tutorial
Programmation en C
Tp1 - Initiation à Java-Eclipse

What's hot (20)

PPT
Reliable Windows Heap Exploits
PDF
Qemu JIT Code Generator and System Emulation
PPTX
Triton and Symbolic execution on GDB@DEF CON China
DOCX
Pengenalan Umum Sistem Operasi dan Struktur Sistem Komputer.
PPTX
为啥别读HotSpot VM的源码(2012-03-03)
PDF
Linux SMEP bypass techniques
PDF
Secure storage updates - SFO17-309
PDF
Introduction to the LLVM Compiler System
PDF
Windows 10 Nt Heap Exploitation (English version)
PDF
Part II: LLVM Intermediate Representation
PPT
CA_7_final_ppt.ppt
PDF
Embedded linux network device driver development
PPTX
GCC RTL and Machine Description
PDF
Alphorm.com Formation MySQL Administration(1Z0-883)
PPT
PPTX
Java version 11 - les 9 nouveautes
PDF
systemd
PDF
Why we love pgpool-II and why we hate it!
PPTX
Redis Reliability, Performance & Innovation
PDF
Support de cours technologie et application m.youssfi
Reliable Windows Heap Exploits
Qemu JIT Code Generator and System Emulation
Triton and Symbolic execution on GDB@DEF CON China
Pengenalan Umum Sistem Operasi dan Struktur Sistem Komputer.
为啥别读HotSpot VM的源码(2012-03-03)
Linux SMEP bypass techniques
Secure storage updates - SFO17-309
Introduction to the LLVM Compiler System
Windows 10 Nt Heap Exploitation (English version)
Part II: LLVM Intermediate Representation
CA_7_final_ppt.ppt
Embedded linux network device driver development
GCC RTL and Machine Description
Alphorm.com Formation MySQL Administration(1Z0-883)
Java version 11 - les 9 nouveautes
systemd
Why we love pgpool-II and why we hate it!
Redis Reliability, Performance & Innovation
Support de cours technologie et application m.youssfi
Ad

Viewers also liked (9)

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

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

PPT
PPTX
Web sockets - Pentesting
PDF
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
PDF
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
PDF
Real time web apps
PPTX
UNIT - 5.pptx Servlets And Database Connectivity
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PDF
Tools. Techniques. Trouble?
PDF
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
PDF
Lecture 2: Servlets
PDF
How to Build Single Page HTML5 Apps that Scale
KEY
The HTML5 WebSocket API
PDF
Building Next Generation Real-Time Web Applications using Websockets
PPT
Top 10 HTML5 Features for Oracle Cloud Developers
PPTX
Intro to WebSockets
PDF
Servlet and JSP
PPT
HTML5 WebSocket: The New Network Stack for the Web
PPTX
Servlets api overview
PDF
Code for Startup MVP (Ruby on Rails) Session 1
PPTX
Enjoying the Move from WCF to the Web API
Web sockets - Pentesting
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
Real time web apps
UNIT - 5.pptx Servlets And Database Connectivity
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Tools. Techniques. Trouble?
Html5 web sockets - Brad Drysdale - London Web 2011-10-20
Lecture 2: Servlets
How to Build Single Page HTML5 Apps that Scale
The HTML5 WebSocket API
Building Next Generation Real-Time Web Applications using Websockets
Top 10 HTML5 Features for Oracle Cloud Developers
Intro to WebSockets
Servlet and JSP
HTML5 WebSocket: The New Network Stack for the Web
Servlets api overview
Code for Startup MVP (Ruby on Rails) Session 1
Enjoying the Move from WCF to the Web API

More from Fabio Tiriticco (12)

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

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Cloud computing and distributed systems.
PPT
Teaching material agriculture food technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Modernizing your data center with Dell and AMD
PDF
KodekX | Application Modernization Development
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
Teaching material agriculture food technology
Per capita expenditure prediction using model stacking based on satellite ima...
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
Modernizing your data center with Dell and AMD
KodekX | Application Modernization Development
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
NewMind AI Monthly Chronicles - July 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Unlocking AI with Model Context Protocol (MCP)
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Dropbox Q2 2025 Financial Results & Investor Presentation

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