Created
October 11, 2013 15:26
-
-
Save dat-vikash/6936680 to your computer and use it in GitHub Desktop.
Play2.2 basic websockets example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) | |
} | |
} |
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");
}
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.
@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
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"…}