Akka Tcp绑定消息使用情况

时间:2016-08-17 13:59:22

标签: scala tcp akka

我正在编写Tcp客户端服务器。 服务器角色已创建。在构造函数中,它绑定到IP和随机端口

我向服务器actor发送一条初始消息以开始通信。 但是,在服务器actor接收Bound消息之前,会收到此初始消息。

在服务器收到我的初始消息之前,有没有办法收到Bound消息? 服务器构造函数代码

ServerActor extends Actor with ActorLogging
{
    var myAddress:InetSocketAddress = new InetSocketAddress(hostName,0)
    val options:List[akka.io.Inet.SocketOption] = List():::List(Tcp.SO.ReuseAddress(true)):::List(Tcp.SO.ReceiveBufferSize(65535))
      manager ! Bind(self, myAddress,1,options) 

    def receive = {
        case b @ Bound(addr) => println(addr)
        myAddress = addr
        case c @ Connected(remoteAddress,localAddress) => 
          log.info("Client Connected. Remote: {} Local: {}", remoteAddress, localAddress)
          remoteConnection = sender()
          remoteConnection ! Register(self)

        case CommandFailed(_: Bind) =>
          log.error("Binding Command Failed. Exiting.")
          context stop self      

        case mRegisterMessage: RegisterMessage =>
          {

              //create register response and send it back
              val mRegisterResponseMessage = new RegisterResponseMessage(true, "IPv4", myAddress.getHostString, myAddress.getPort)
              sender() ! RegisterResponseMessage

          }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用http://doc.akka.io/api/akka/2.4/index.html#akka.actor.Stash

您可以重新定义preStart方法,然后首先执行

context.become({ case b @ Bound(addr) =>
 ...
 unstashAll() 
 context.unbecome()})

所有邮件都将被隐藏,只会处理Bound条消息。然后,当收到消息时,您将切换到标准receive,并且您的处理程序将接收所有消息。