Basic Routing Example and Web Socket Example

I am trying to learn how to use web sockets in Play 2.1, and I am unable to get the web socket url to work with my application routing configuration. I started with the new Play app and Playback Platform Documentation on websites .

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 the 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 websocket with the URL ws://localhost:9000/wstest (using the example code websocket.org/echo.html ), I watched the sample/scala/websocket-chat application that comes with the platform Play, and uses the routing configuration file to refer to the websocket, for example:

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

I tried replacing my website URL with @routes.Application.wstest.webSocketURL() and @routes.Application.wstest . The first one does not compile. The second compiles, but the client and server do not exchange messages.

How can I use the Play routing configuration to access this web schedule? What am I doing wrong here?


Edit

Here is a screenshot of my compilation error: "Unable to find the HTTP HTTP header here":

compilation-error

+7
source share
2 answers

Without a compiler error, it's hard to guess what could be the problem.

Or you must use parens due to an implicit request, i.e. @routes.Application.wstest().webSocketURL() , or you don’t have an implicit request in the scope that is needed to call webSocketURL.

+6
source

Marius is right that there was no implicit request in the area. Here's how to get it in the area:

Update the index function in the controller:

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

Add the query as the curried parameter to index.scala.html :

 @(message: String)(implicit request: RequestHeader) @main(message) { <script> var output; function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket("@routes.Application.wstest.webSocketURL()"); . . . 

And now RequestHeader is in scope.

+2
source

All Articles