Skip to content

Instantly share code, notes, and snippets.

@rafaelgarrote
Forked from kafecho/gist:5353393
Created February 9, 2016 11:39
Show Gist options
  • Save rafaelgarrote/01dfcfb4f1dac1fdf983 to your computer and use it in GitHub Desktop.
Save rafaelgarrote/01dfcfb4f1dac1fdf983 to your computer and use it in GitHub Desktop.
Example of how to handle UDP connection with Akka 2.2-M2
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment