Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package misc
- import java.net.InetSocketAddress
- import akka.actor.{ActorSystem, Props, Actor}
- import akka.io.{IO, Tcp}
- import akka.util.ByteString
- class Server extends Actor {
- import Tcp._
- import context.system
- IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 4321))
- def receive = {
- case b @ Bound(localAddress) =>
- // do some logging or setup ...
- case CommandFailed(_: Bind) => context stop self
- case c @ Connected(remote, local) =>
- val handler = context.actorOf(Props[SimplisticHandler])
- val connection = sender()
- connection ! Register(handler)
- }
- }
- object SimplisticHandler {
- object PacketByteString{
- def unapply(bs: ByteString): Option[(ByteString, ByteString)] = {
- val (left, right) = (bs.takeWhile(_ != '_'), bs.dropWhile(_ != '_'))
- right match {
- case ByteString.empty => None
- case x if x == ByteString('_') => Some(left, ByteString.empty)
- case _ => Some(left, right.tail)
- }
- }
- }
- implicit class PacketByteString(b: ByteString) {
- def apply(b: ByteString) = new PacketByteString(b)
- }
- }
- class SimplisticHandler extends Actor {
- import Tcp._
- import SimplisticHandler._
- def receive = receiveBs(ByteString.empty)
- def receiveBs(bs: ByteString): Receive = {
- case Received(data) =>
- def process: PartialFunction[ByteString, Unit] = {
- case PacketByteString(packet, rest) =>
- sender() ! Write(packet)
- process(rest)
- case rest =>
- context.become(receiveBs(rest))
- }
- process(bs.concat(data))
- case PeerClosed =>
- context stop self
- }
- }
- object Run extends App {
- val actorSystem = ActorSystem("TcpServer")
- actorSystem.actorOf(Props[Server])
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement