Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Play framework routing and web sockets example

I'm trying to learn how to use web sockets in Play 2.1, and I'm having trouble getting the web socket URL to work with my app's routing configuration. I started with a new Play application and the Play framework documentation on websockets.

Here is my conf/routes:

# Home page
GET   /               controllers.Application.index

# Websocket test site
GET   /wstest         controllers.Application.wstest

Then I added the wstest function to my controller class:

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Websocket Test"))
  }

  def wstest = WebSocket.using[String] { request =>
    // Log events to the console
    val in = Iteratee.foreach[String](println).mapDone { _ =>
      Logger.info("Disconnected")
    }

    // Send a single 'Hello!' message
    val out = Enumerator("Hello!")

    (in, out)
  }
}

However, so far, I can only access the websocket with the URL ws://localhost:9000/wstest (using the sample code at websocket.org/echo.html). I was looking at the sample/scala/websocket-chat app that comes with the Play framework, and it uses the routing configuration file to reference the websocket, like this:

var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("@routes.Application.chat(username).webSocketURL()")

I tried replacing my websocket URL with @routes.Application.wstest.webSocketURL() and @routes.Application.wstest. The first one doesn't compile. The second one compiles, but the client and server don't exchange any messages.

How can I use my Play routing configuration to access this websocket? What am I doing wrong here?


Edit

Here is a screenshot of my compilation error, "Cannot find any HTTP Request Header here":

compilation-error

like image 846
David Kaczynski Avatar asked May 17 '13 17:05

David Kaczynski


1 Answers

Without the compiler error it's hard to guess what might be the problem.

Either you have to use parens because of the implicit request, i.e. @routes.Application.wstest().webSocketURL(), or you have no implicit request in scope which is needed for the webSocketURL call.

like image 129
Marius Soutier Avatar answered Nov 03 '22 00:11

Marius Soutier