Play Framework WebSocket in Java

What is WebSocket? When should I use it?

WebSocket is an amazingly fast, easy to use and full-duplex way to communicate between client and server. WebSocket is recommended if you want a fast real-time application like a bid application, or a real time poker game. It’s easy to broadcast messages between users (or just send message to some of them).

Play WebSocket Java

WebSocket in PlayFramework 2.4 (Java)

Play framework has a built-in WebSocket class, which will do all the work for you (for example the handshake). You only have to override one function in which you can define what to do with a message, and what to do when the socket is closed.

onReady is the function called when the WebSocket connection is ready. You can send any initial data to the connected user there.

in.onMessage is the function that is called on all messages. The above example is a very simple chat application, every message the server receives will be sent to all connected users.

in.onClose is the function that is called when the socket is closed.

More complex application with WebSocket

If you want to make a more complex application with WebSocket, I recommend you to do the following. I was using Gson as the Json parser, but I’m sure that any other Json parsers can do it for you.

I recommend you to use this class as the base communication object. It has two fields, message type defines what kind of message the client sent, or what kind of message the server sent to the client(s). You can decide what kind of JSON body must be in the body, what are required fields, enums, and other stuff. After you decided the kind of message it is, you can parse the message to the class you want. In the SocketMessageBody you can define fields, that ALL messages must contain, for example a secret token, userID to identify the user or a timestamp that tells us when the message was sent.

If you don’t want to send these fields down to the client, you can define two classes, one for input messages, and one for output. These message objects can extend the SocketMessageBody like so:

After you know what kind of message you received, you can parse the body into the desired class like:

This example shows a code snippet, that handles a “USER_JOINED” message type. Parses the body to UserJoinsedGameInputBody (which class extends InputBody), adds the user to the lobby, and sends the room list as the response.

With WebSockets you can communicate with any client (WebBrowser, Android, iPhone, WindowsPhone, etc.). I’ll give you an example client implementation for Android and iOS soon, so keep an eye out & sign up for our newsletter!

Alex Sükein

Alex Sükein

- Süxy, can you tell me about robust software development Nasa uses?
- Yes. If we have a final exam tomorrow.