Fede
Fede

Reputation: 874

Why does connection close automatically after 1 minute using Akka TCP?

I'm writing an Interactive Broker API using Scala and Akka actors.

I have a Client actor that connects to the server and communicate with the IO manager to send requests and receive responses from TWS. The connection works fine and I'm able to send a request and get the response.

Then I receive automatically a PeerClosed message from the IO manager after 1 minute. I would like that the connection stays open unless I explicitly close it. I tried to set keepOpenOnPeerClosed = true but it changes nothing.

Here is the Actor:

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
      }    

I don't have the same behaviour if I connect using IBJts API (using a standard Java Socket)

Upvotes: 4

Views: 1400

Answers (1)

Bomgar
Bomgar

Reputation: 625

Have you tried it with the keep alive option?

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

Upvotes: 2

Related Questions