Advertisement
Guest User

Untitled

a guest
Feb 17th, 2015
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.43 KB | None | 0 0
  1. import java.net.InetSocketAddress
  2.  
  3. import akka.actor._
  4. import akka.io.Tcp
  5. import akka.util.ByteString
  6. import org.joda.time.DateTime
  7. import scala.concurrent.duration._
  8.  
  9. class TcpBenchConnectionHandler(remote: InetSocketAddress, connection: ActorRef) extends Actor with ActorLogging {
  10.  
  11.   import context.dispatcher
  12.  
  13.   // We need to know when the connection dies without sending a `Tcp.ConnectionClosed`
  14.   context.watch(connection)
  15.  
  16.   def sendPackets(sender: ActorRef) : Runnable = return new Runnable {
  17.       def run() = {
  18.         val packet = new Packet(DateTime.now())
  19.         sender ! Tcp.Write(packet.toByteString)
  20.       }
  21.     }
  22.  
  23.   def receive: Receive = {
  24.     case Tcp.Received(data) =>
  25.       val text = data.utf8String.trim
  26.       text match {
  27.         case "close" => {
  28.           context.stop(self)
  29.         }
  30.         case "start" => {
  31.           val exec = sendPackets(sender)
  32.           context.system.scheduler.schedule(1 seconds, 1 seconds) {
  33.             exec.run()
  34.           }
  35.           exec.run()
  36.         }
  37.         case _       => {
  38.           sender ! Tcp.Write(ByteString.fromString("not valid"))
  39.         }
  40.       }
  41.     case _: Tcp.ConnectionClosed =>
  42.       log.debug("Stopping, because connection for remote address {} closed", remote)
  43.       context.stop(self)
  44.     case Terminated(`connection`) =>
  45.       log.debug("Stopping, because connection for remote address {} died", remote)
  46.       context.stop(self)
  47.   }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement