Akka Socket每个演员

时间:2013-01-18 21:54:40

标签: multithreading sockets scala akka actor

使用Scala和Akka IO有一种方法可以让一个Actor严格用于监听,然后在建立连接时创建一个新的actor,然后负责该Socket(阅读,写作等)?

到目前为止,我有这个。问题是Server actor正在接收数据。我想将套接字的所有权转移到新创建的Client actor,以便它接收与套接字相关的任何消息。有谁知道怎么做?

编辑:添加解决方案。我只需要将ActorRef传递给accept

的curried参数
import akka.actor._
import akka.actor.IO.SocketHandle
import java.net.InetSocketAddress


/**
 * Purpose:
 * User: chuck
 * Date: 17/01/13
 * Time: 5:37 PM
 */
object Main {

  class Server extends Actor {

    override def preStart() {
      IOManager(context.system) listen new InetSocketAddress(3333)
    }

    def receive = {

      case IO.NewClient(server) =>

        val client = context.actorOf(Props(new Client()))
        server.accept()(client)
        println("Client accepted")

      case IO.Read(socket, bytes) =>
        println("Server " + bytes)


    }
  }

  class Client() extends Actor {

    def receive = {

      case IO.Read(socket, bytes) =>
        println("Client " + bytes)

      case IO.Closed(socket, reason) =>
        println("Socket closed " + reason)

    }

  }

  def main(args: Array[String]) {
    val system = ActorSystem()
    system.actorOf(Props(new Server))
  }

}

谢谢!

1 个答案:

答案 0 :(得分:3)

让答案更加明显:

来自ServerHandle的{​​{3}}:

def accept ()(implicit socketOwner: ActorRef): SocketHandle
  应该接收与SocketChannel关联的事件的

socketOwner ActorRef。将使用当前Actor的ActorRef   隐式。

如果没有将任何内容传递给curried参数(仅调用server.accept()),则当前Actor(Server)将从SocketChannel接收事件。但是,正如方法签名所示,您可以将ActorRef传递给curried参数,以便SocketChannel上发生的事件将由此新Actor处理。

让我们接受问题所有者添加的解决方案:

def receive = {
  case IO.NewClient(server) =>
      val client = context.actorOf(Props(new Client()))
      server.accept()(client) // Transferring ownership of the socket to a new Actor
      println("Client accepted")

  case IO.Read(socket, bytes) =>
      println("Server " + bytes)
}