Skip to content

Instantly share code, notes, and snippets.

@dat-vikash
Created October 11, 2013 15:26
Show Gist options
  • Save dat-vikash/6936680 to your computer and use it in GitHub Desktop.
Save dat-vikash/6936680 to your computer and use it in GitHub Desktop.
Play2.2 basic websockets example
//This shows an updated websocket example for play2.2.0 utilizing Concurrent.broadcast vs Enumerator.imperative, which
// is now deprecated.
object Application extends Controller {
def index = WebSocket.using[String] { request =>
//Concurernt.broadcast returns (Enumerator, Concurrent.Channel)
val (out,channel) = Concurrent.broadcast[String]
//log the message to stdout and send response back to client
val in = Iteratee.foreach[String] {
msg => println(msg)
//the channel will push to the Enumerator
channel push("RESPONSE: " + msg)
}
(in,out)
}
}
@dat-vikash
Copy link
Author

This can be tested using Chrome's console:

var ws = new WebSocket("ws://localhost:9000/ws");
ws.onmessage = function( message ) { console.log( message ); };
ws.send("This is a test");

MessageEvent {ports: Array[0], data: "RESPONSE: This is a test", source: null, lastEventId: "", origin: "ws://localhost:9000"…}

@porl
Copy link

porl commented Oct 22, 2013

Interestingly I got an error trying to use the console test code you posted above. I had to change the last line to be inside a function:

ws.onopen = function() {
    ws.send("This is a test");
}

@amitabh123
Copy link

How do I push a message to the client without waiting for a request from it ? This code only allows sending message in response to a message received from the client.

@dat-vikash
Copy link
Author

@amitabh123 you can just use the channel's push method. If your class has access to the channel, then all you would need to do is issue pushes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment