Skip to content

Instantly share code, notes, and snippets.

@v6ak
Created April 19, 2011 10:37
Show Gist options
  • Select an option

  • Save v6ak/927108 to your computer and use it in GitHub Desktop.

Select an option

Save v6ak/927108 to your computer and use it in GitHub Desktop.
Pieces of code demonstrating Play!s WebSocket in Scala using the (relatively) low-level way.
object SomeWSHandler extends WebSocketController{
def handle() {
val rs = RequestScope.current
// handle new sockets
if (request isNew) {
outbound.send("Hello from server!")
}
// handle new messages in existing socket
val newPromise = rs.remove(FutureKey)
for(promise <- newPromise){
promise.get match{
case frame: WebSocketFrame => {
if(frame isBinary){
outbound send "binary msg: " + frame.binaryData
}else{
outbound send "text msg: " + frame.textData
frame.textData match { // match commands
case ":close!" =>
outbound send "Bye!"
outbound.close()
case _ => // Other commands are silently ignored. It this line was missing, other commands would cause scala.MatchError
}
}
}
case _: WebSocketClose => println("Goodbye.")
}
}
// start waiting for next message and suspend
if (inbound isOpen) {
val eventPromise = inbound.nextEvent
rs(FutureKey) = eventPromise
request.isNew = false
throw new Invoker.Suspend(eventPromise)
}
}
}
import play.mvc.Http.Request
import RequestScope.Variable
final class RequestScope (val request: Request){
private val store = {
val Key = "__RequestScope"
val args = request.args
if(args containsKey Key){
println("load RS")
(args get Key).asInstanceOf[collection.mutable.Map[Variable[_], Any]]
}else{
println("new RS")
val map = collection.mutable.Map[Variable[_], Any]()
args.put(Key, map)
map
}
}
def update[T](variable: Variable[T], value:T){
store(variable) = value
}
def remove[T](variable: Variable[T]): Option[T] = {
val removed = store remove variable
removed.asInstanceOf[Option[T]]
}
}
object RequestScope{
final class Variable[T]
def current = new RequestScope(Request.current())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment