Advertisement
Guest User

Untitled

a guest
Aug 13th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.82 KB | None | 0 0
  1. package misc
  2.  
  3. import java.net.InetSocketAddress
  4.  
  5. import akka.actor.{ActorSystem, Props, Actor}
  6. import akka.io.{IO, Tcp}
  7. import akka.util.ByteString
  8.  
  9. class Server extends Actor {
  10.  
  11.   import Tcp._
  12.   import context.system
  13.  
  14.   IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 4321))
  15.  
  16.   def receive = {
  17.     case b @ Bound(localAddress) =>
  18.     // do some logging or setup ...
  19.  
  20.     case CommandFailed(_: Bind) => context stop self
  21.  
  22.     case c @ Connected(remote, local) =>
  23.       val handler = context.actorOf(Props[SimplisticHandler])
  24.       val connection = sender()
  25.       connection ! Register(handler)
  26.   }
  27.  
  28. }
  29.  
  30. object SimplisticHandler {
  31.   object PacketByteString{
  32.     def unapply(bs: ByteString): Option[(ByteString, ByteString)] = {
  33.       val (left, right) = (bs.takeWhile(_ != '_'), bs.dropWhile(_ != '_'))
  34.       right match {
  35.         case ByteString.empty           => None
  36.         case x if x == ByteString('_')  => Some(left, ByteString.empty)
  37.         case _                          => Some(left, right.tail)
  38.       }
  39.     }
  40.   }
  41.  
  42.   implicit class PacketByteString(b: ByteString) {
  43.     def apply(b: ByteString) = new PacketByteString(b)
  44.   }
  45. }
  46.  
  47. class SimplisticHandler extends Actor {
  48.   import Tcp._
  49.  
  50.   import SimplisticHandler._
  51.  
  52.   def receive = receiveBs(ByteString.empty)
  53.  
  54.   def receiveBs(bs: ByteString): Receive = {
  55.     case Received(data) =>
  56.       def process: PartialFunction[ByteString, Unit] = {
  57.           case PacketByteString(packet, rest) =>
  58.             sender() ! Write(packet)
  59.             process(rest)
  60.           case rest =>
  61.             context.become(receiveBs(rest))
  62.       }
  63.       process(bs.concat(data))
  64.     case PeerClosed     =>
  65.       context stop self
  66.   }
  67. }
  68.  
  69. object Run extends App {
  70.  
  71.   val actorSystem = ActorSystem("TcpServer")
  72.   actorSystem.actorOf(Props[Server])
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement