Wednesday, September 19, 2012

HTML5 WebSocket using Play Framework 2.0

Recently, I learned about HTML5 WebSockets. It is pretty cool. During the handshake onReady event, I cache the out stream in a static member variable. Another user action that writes to this stream. This simulates a typical order processing scenario, where a customer places order and store owner gets live order notification.

routes
GET / controllers.Application.index()
GET /order controllers.Application.order()

Application.java
package controllers;
import play.*;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.*;
public class Application extends Controller {
  public static WebSocket.Out outCached=null;
  public static Result order() {
  if (outCached!=null)
    outCached.write("Another User Placed an order");
    return ok("Success");
  }
  public static WebSocket index() {
    return new WebSocket() {// Called when the Websocket Handshake is done.
      public void onReady(WebSocket.In in, WebSocket.Out out) {
        outCached=out;// For each event received on the socket,
        in.onMessage(new Callback() {
          public void invoke(String event) {
          Logger.info(event);// Log events to the console
        } 
      });
      in.onClose(new Callback0() {// When the socket is closed.
      public void invoke() {
        outCached=null;
        Logger.info("Disconnected");
      }
    });
    out.write("Hello!");// Send a single 'Hello!' message
    }
  };
}
}
Test Client
I used the WebSocket.org's echo client page in the latest chrome browser. I set the location to ws://localhost:9000.
http://www.websocket.org/echo.html Then place an order from another browser using this link: http://localhost:9000/order
References