Follow my blog with Bloglovin

Friday, January 10, 2014

Playramework 2 : WebSocket Continious Streaming Java Example

Refer to my earlier post to setup Play with Spring.

Create controller class as:


package controllers;

import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

import play.libs.Akka;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.WebSocket;
import scala.concurrent.duration.Duration;

@Component
public class WebSocketController {

       public WebSocket<String> websocket() {
              return new WebSocket<String>() {
                     public void onReady(final WebSocket.In<String> in, final WebSocket.Out<String> out) {
                           in.onMessage(new Callback<String>() {
                                  public void invoke(String event) {
                                         System.out.println(event);
                                         out.write("Hello! Received "+event);
                                  }
                           });
                           in.onClose(new Callback0() {
                                  public void invoke() {
                                         System.out.println("Disconnected");
                                  }
                           });

                           class StreamNumbers implements Runnable{
                                  private int i = 0;

                                  @Override
                                  public void run() {
                                         out.write(String.valueOf(i));
                                         i++;
                                  }

                           }

                           Akka.system().scheduler().schedule(
                                         Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds start immidiately
                                         Duration.create(30, TimeUnit.SECONDS),     //Frequency 30 seconds
                                         new StreamNumbers(),
                                         Akka.system().dispatcher()
                                         );
                     }
              };
       }
}

Add routes entry in conf/routes file as:
GET        /websocket                       @controllers.WebSocketController.websocket()

Run the Play application and test it with http://www.websocket.org/echo.html by using location as ws://localhost:9000/websocket

Popular Posts