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;

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) {
                                         out.write("Hello! Received "+event);
                           in.onClose(new Callback0() {
                                  public void invoke() {

                           class StreamNumbers implements Runnable{
                                  private int i = 0;

                                  public void run() {


                                         Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds start immidiately
                                         Duration.create(30, TimeUnit.SECONDS),     //Frequency 30 seconds
                                         new StreamNumbers(),

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

Run the Play application and test it with by using location as ws://localhost:9000/websocket

Popular Posts