Created
February 18, 2011 07:37
-
-
Save buka/833384 to your computer and use it in GitHub Desktop.
example to illustrate different ways of using websockets...
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
package sample | |
import akka.actor._ | |
import akka.http._ | |
class SampleService extends Actor with Endpoint | |
{ | |
self.dispatcher = Endpoint.Dispatcher; | |
def hook(uri:String) = true | |
def provide(uri:String) = uri match { | |
case "/socket0" => Actor.actorOf[Socket0Actor].start | |
case "/socket1" => Actor.actorOf[Socket1Actor].start | |
} | |
override def preStart = Actor.registry.actorsFor(classOf[RootEndpoint]).head ! Endpoint.Attach(hook, provide) | |
def receive = handleHttpRequest | |
} | |
// | |
// act like a regular mist endpoint handler and do things explicitly | |
// | |
class Socket0Actor extends Actor | |
{ | |
override def preStart = Scheduler.scheduleOnce(self, "Message for socket0", 5, java.util.concurrent.TimeUnit.SECONDS) | |
var producer:Option[ActorRef]= None | |
def receive = | |
{ | |
case get:Get => get OK "it works" | |
case connect:Connect => | |
log.slf4j.info("Socket0 connected.") | |
val p = Actor.actorOf{new Actor with WebSocketProducer{def receive = handleWebSocketRequest}}.start | |
p ! connect | |
producer = Some(p) | |
case frame:Frame => | |
val s = new String(frame.data) | |
log.slf4j.info("Socket0 received: "+s) | |
case s:String => producer.foreach {_ ! s} | |
case a:Array[Byte] => producer.foreach {_ ! a} | |
case Disconnect(_) => | |
log.slf4j.info("Socket0 disconnected.") | |
producer = None | |
case other:RequestMethod => other NotAllowed "unsupported request" | |
} | |
} | |
// | |
// be a ws producer | |
// | |
class Socket1Actor extends Actor with WebSocketProducer | |
{ | |
override def preStart = Scheduler.scheduleOnce(self, "Message for socket1", 5, java.util.concurrent.TimeUnit.SECONDS) | |
def recv:Receive = | |
{ | |
case get:Get => get OK "it works" | |
case frame:Frame => | |
val s = new String(frame.data) | |
log.slf4j.info("Socket1 received: "+s) | |
case other:RequestMethod => other NotAllowed "unsupported request" | |
} | |
def receive = {handleWebSocketRequest orElse recv} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment