Created
April 10, 2013 10:09
-
-
Save kafecho/5353393 to your computer and use it in GitHub Desktop.
Example of how to handle UDP connection with Akka 2.2-M2
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 org.kafecho.learning.akka | |
import java.net.InetSocketAddress | |
import akka.actor.Actor | |
import akka.actor.ActorLogging | |
import akka.actor.ActorSystem | |
import akka.actor.Props | |
import akka.actor.actorRef2Scala | |
import akka.io.IO | |
import akka.io.UdpFF | |
import akka.io.UdpFF.Bind | |
import akka.io.UdpFF.Bound | |
import akka.io.UdpFF.Received | |
import akka.io.UdpFF.Unbind | |
object Connect | |
object Disconnect | |
object AkkaIOTest extends App { | |
implicit val system = ActorSystem("UDPTest") | |
class UDPConnection(port:Int) extends Actor { | |
val handler = system.actorOf(Props[UDPReceiver], name = "UDPReceiver") | |
def receive = { | |
case Connect => | |
IO(UdpFF) ! Bind(handler, new InetSocketAddress(port)) | |
case Bound => | |
val worker = sender | |
context.become { | |
case Disconnect => | |
worker ! Unbind | |
context.become(receive) | |
} | |
} | |
} | |
class UDPReceiver extends Actor with ActorLogging { | |
def receive = { | |
case Received(data, from) => log.info("Received a UDP Packet {} sent from {}.", data, from) | |
case _ => | |
} | |
} | |
val udpConnection = system.actorOf(Props(new UDPConnection(1234))) | |
udpConnection ! Connect | |
Thread.sleep(2000) | |
udpConnection ! Disconnect | |
Thread.sleep(2000) | |
udpConnection ! Connect | |
Thread.sleep(2000) | |
udpConnection ! Disconnect | |
} |
Oops. Only saw your comment yesterday. I need to check if Akka IO supports UDP multicast. When I looked a while back it didn't.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 23 should most probably be context.actorOf
Glad you're enjoying it, I think it's a far superior UDP API :-)