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).


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.

import play.mvc.WebSocket;
import java.util.ArrayList;
import java.util.List;
public class ChatSocket extends WebSocket<String> {
   private static List<Out<String>> outputs = new ArrayList<>();
   public WebSocket<String> open() {
      return new ChatSocket();
   public void onReady(In<String> in, final Out<String> out) {
      in.onMessage(message -> {
         outputs.forEach(out -> out.write(message));
      in.onClose(() -> {

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.

public class SocketMessageObject {
   public String messageType;
   public JsonElement body;
   public SocketMessageObject() {
   public SocketMessageObject(String messageType, SocketMessageBody body) {
      this.messageType = messageType;
      this.body = new Gson().toJsonTree(body);

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:

public class InputBody extends SocketMessageBody {
   public String userId;
   public JsonElement action;

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

in.onMessage(messageObject -> {
    SocketMessageObject parsedMessageObject = fromJson(messageObject, SocketMessageObject.class);
    if("USER_JOINED".equals(parsedMessageObject.messageType)) {
        UserJoinedGameInputBody body = fromJson(parsedMessageObject.body, UserJoinedGameInputBody.class);
        addToLobby(body.userId, out);
        out.write(message("AVAILABLE_ROOMS", new RoomListOutputBody(rooms)));

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!


Wanari is a custom software development company, founded in 2000. This is our tech blog. We strive for new technologies and building challenging concepts using them. Get to know us a bit more by visiting our Insta or LinkedIn pages!

member photo

His favorite technologies are AngularJS and Java 8. He's been at Wanari as a full stack developer for almost 3 years.

Latest post by Alex Sükein

Solutions for a filterable sortable pageable list in Spring