Getting started with WebSockets using Play framework

Posted by

    Power socket covered by a web made by the Nephila Clavipes
    Power socket covered in spider webbing - a literal WebSocket

    In the beginning, there were only web pages. As usage of the web exploded, the need for web applications grew proportionally. But the early web applications had a restriction: Every action had to be initiated by the user - there was no way for the server to tell the user when there was new data available. During the last 10 years, some solutions have been found, but they had drawbacks. Until WebSockets came along.

    The web as we know it is largely based on a simple concept: Your browser sends a request to the server, the server responds with a document which you can then view in the browser, and at a later point in time, you can choose to navigate elsewhere and start the same process over again. This has been the way things have been done ever since the web was born. Then around 2005, web pages began using AJAX to allow content to be downloaded asynchronously, meaning at a given point in time (or with a given frequency). For instance, with AJAX, a map shown on a web page could update its visible area whenever the user panned by dragging. With older technologies, the user had to reload the whole page to update the map, but now it would seem as if the map was updating itself live. And with AJAX, you could have an online e-mail application check for new mail every minute, by itself. No more clicking the “Get mail” button to reload the page!

    But even with AJAX, web applications didn’t really offer proper two-way communication, as all requests were either a result of user action sent to the server or of some pre-programmed interval in the client-side JavaScript. There was no way for the server to simply provide new data to the client directly. This is the problem that WebSockets tries to solve.

    Instead of sending requests that are completed when data is received, WebSockets open a connection through which subsequent messages can be sent, in both directions. The WebSocket protocol is supported by most modern browsers: Chrome 14, Firefox 6, Safari 6, Opera 12.10 and Internet Explorer 10.

    Setting up

    You can’t just start using Websockets straight away in your code, like with CSS. We do need some extra plumbing done first. This might scare a lot of you away, but we’ll walk you through it smooth and safe.

    Websockets are supported in modern browsers via JavaScript. You can write all your “send to server”-things right now if you’d like. But there’s a catch. You need a server. And a server doesn’t automatically understand what you’re sending it, be it text messages, images, or something else.

    So we need to do some configuration on our server. First, it needs to get support for Websockets, and this must be done manually. There are many options for us out there. Two of them are node.js and Play Framework, among many alternatives. These are server-like apps that you install on the server (or your computer) to be able to set up code that responds to whatever your JavaScript sends them. Play does a lot more than just handle WebSockets, but that’s out of scope of this introductory article.

    Getting started with Play

    1. Download Play

    Start by visiting and click the big green download button. We’ve built and tested our code on version 2.2.1, but most likely any 2.x-version would work too. But go for the classic distribution (if you get multiple choices on the download page). Save that zip-file to your computer and what for circa 100 MB to get sucked down.

    If you want to take it straight from the source, Play framework has its own installation guide, and a very competent one.

    Now unzip all the files to a convenient location on your computer.

    2. Installing Play

    Starting and stopping the Play server is done through the command line. We also create new websites there. So first things we need to set the system variable “play” to the path to where we just unzipped Play.

    On Mac OS X, just open Terminal and write “export PATH=$PATH:/XXX” where XXX is the exact path to you Play installation. After this you can send commands to Play just by starting a new line with “play “.

    Let’s see if Play works! Just open a Terminal window and write “play help” and press enter. This should show you some basic info about the Play framework, which proves to us that it actually works and that all steps went well so far.

    3. Create our first project

    Now with Play installed we can start a new application, or project. Just type “play new testWebsockets” and hit enter. The command line will ask you for a full name of the app, write something that helps you understand what it is. We will test Websockets so something about that would be good enough.

    After naming the app you get the question if you’re creating a Scala app or a Java app. Chose the Java alternative. Done!

    4. Start that app

    Just “cd” into your new app-folder (“cd testWebsockets”) and write “play” to start it up. Your app is now active and running on your local Play server.

    The last thing to be done is to compile your source code to localhost. This is done by writing “run” in the same folder in Terminal. Now all the source files that Play already generated for you gets compiled and published to http://localhost:9000. So try it in your browser! Don’t mind the errors, we’ll iron them out later.

    It’s alive!

    With Play framework up and running we now have a server that understands Websockets. It can receive messages and information over that protocol, and can also send things back. The Javascript can hammer the server with requests over the same live Websocket connection, instead of over the normal http-protocol. But, the server only understands that Websockets exists and that it can be used, not exactly what to do with each request. It’s like being a limp baseball fan - you fully understand the game, but you can’t play it.

    Enter Java

    With Java we can set up a small program to listen for the incoming messages/requests via the Websocket-protocol. We then analyze what is sent and can do something about it. For instance we could save the data to a database if we want. The Java-code will decide what will be done and what kind of response the server should send back to our Javascript on the client-side.

    A basic example is that we could have a “robot” in our Java-code answer an incoming string with some other string. If the user types “Time?” in a textbox and sends that to the server, our robot could respond with the current time. The Javascript would then place that response in the DOM. All this without the connection ever going down, and with no page refreshes - or extra http-requests like with Ajax!

    When you start to grasp the concept of all this, you see how powerful this is for games. Instant and concurrent communication with the server, on multiple clients.

    So you see, all these three components must work together for Websockets to work. You can of course switch out Play and Java for Node.js and Javascript on the server if you want to. Or to something completely different.


    This example demonstrate how the flow of a typical websocket app can be. I have made the example as plain and straightforward as possible. Stripping away classes and libraries that isn’t really necessary. Even though the extra libraries are probably very useful later, when you want to create larger apps.

    When the browser want to go to a webpage. It sends a request to a server, which sends a response back to the visitor. Lets take a look at what the server is doing when its serving websocket responses.


    Playframework app overview

    SimpleChat uses three files to serve responses back to visitors. This is ofcourse a lie. And depending on your size of your app, it will naturally have lots of other files. But this isnt anything we need to consider at the moment.

    The three files on the server side are, and routes.

    To get Playframework to display anything, the routes file will point to methods in the Application class which render the views. In SimpleChat, there is only one view, which is rendered here:

    The index.html includes the ws.js script by calling the routes file that get to render the js file with this method:

    The last method to implement is the websocket interface. Which handles the incoming “ws:” request. The clients request will be routed through routes, to the method below.

    The method “wsInterface” is returning a websocket instance. The only method “onReady” is called after the Playframework has done the handshake. Nothing complicated in this method. It only passes the WebSocket.In, and WebSocket.Out variables to the SimpleChat class “start” method.

    SimpleChat class has three important things going on.

    1. Somewhere to store the sockets
      1. SimpleClass is storing all the sockets in a List called “connections”
    2. A way to get incoming messages
      1. The method of instance “in” which is called “onMessage” is handling all incoming messages.
    3. A way to push messages:
      1. Method “notifyAll” is iterating the List where the sockets is stored, and sending messages with instancemethod “write”.


    The routes file binds incoming requests to the application. One line for each requests. The javascript request to get ws.js is also present, as the index.html is requesting it when it's being rendered.


    After the server has responded to the requests with html and js files, the browser will be running the downloaded js script.

    The ws.js file starts by creating a new socket. Since mozilla has implemented the websocket in a slightly different way, it checks to see which browser the client is requesting from.

    The websocket class is taking one parameter, which is the request url to the interface. This is registered at the routes file in Playframework. The method “webSocketURL(request)” is returning a URL with “ws:” as protocol.

    By calling new WebSocket(), the client is handshaking with the interface and returning a connected websocket. Whenever the server is sending a message to the client, it will be pushed to the method “socket.onmessage()”. And the client can push messages through socket.send().

    Playframework: after handshaking


    The result is an open websocket which communicates two ways with the server through js. Everytime someone is sending in a message, it will be broadcasted to the other clients.

    Playframework: broadcasting all the things!


    Take a look at or download the files at github, if you want to inspect or play with SimpleChat: Simplechat at github