为什么使用Akka TCP在1分钟后自动关闭?

时间:2014-12-30 18:54:20

标签: scala akka akka-io

我正在使用Scala和Akka演员编写Interactive Broker API。

我有一个客户端actor连接到服务器并与IO管理器通信以发送请求并从TWS接收响应。连接正常,我可以发送请求并获得响应。

然后我在1分钟后自动收到来自IO管理器的PeerClosed消息。我希望连接保持打开,除非我明确关闭它。我试图设置keepOpenOnPeerClosed = true,但它什么都没改变。

这是演员:

class Client(remote: InetSocketAddress, clientId: Int, extraAuth: Boolean, onConnected: Session => Unit, listener: EWrapper) extends Actor {
    final val ClientVersion: Int = 63
    final val ServerVersion: Int = 38
    final val MinServerVerLinking: Int = 70

    import Tcp._
    import context.system

    IO(Tcp) ! Connect(remote)

    def receive = {

        case CommandFailed(_: Connect) =>
          print("connect failed")
          context stop self

        case c@Connected(remote, local) => {

          val connection = sender()
          connection ! Register(self, keepOpenOnPeerClosed = true)
          context become connected(connection,1)
          val clientVersionBytes = ByteString.fromArray(String.valueOf(ClientVersion).getBytes() ++ Array[Byte](0.toByte))
          println("Sending Client Version " + clientVersionBytes)
          sender() ! Write(clientVersionBytes)
       }
     }
      def connected(connection: ActorRef, serverVersion: Int): Receive = {
        case request: Request =>
          print("Send request " + request)
          connection ! Write(ByteString(request.toBytes(serverVersion)))
        case CommandFailed(w: Write) =>
          connection ! Close
          print("write failed")
        case Received(data) => {
          println(data)
          implicit val is = new DataInputStream(new ByteArrayInputStream(data.toArray))
          EventDispatcher.consumers.get(readInt()) match {
            case Some(consumer) => {
              consumer.consume(listener, serverVersion)
            }
            case None => {
              listener.error(EClientErrors.NoValidId, EClientErrors.UnknownId.code, EClientErrors.UnknownId.msg)
            }
          }
        }
        case _ : ConnectionClosed => context stop self
      }    

如果我使用IBJts API连接(使用标准Java套接字),我就不会有相同的行为

1 个答案:

答案 0 :(得分:2)

您是否尝试使用keep alive选项?

sender ! Tcp.SO.KeepAlive(on = true)