7 Replies Latest reply: Jan 18, 2013 5:50 AM by EJP RSS

    Troubles with timeout using java.nio.channels and non-blocking sockets

      I have a server application that employs java.nio.channels with non-blocking sockets.
      The server waits for connections. The client should connect and be first in sending data.
      Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.

      The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
      My code looks as follows:

      Selector oSel;
      SocketChannel oSockChan;
      Socket oSock;
      SelectionKey oSelKey;
      Iterator<SelectionKey> oItSelKeys;
      int iCurrState, iMask, iCount;

      iCurrState = INT_SERVER_WORKING;
      iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
      while ( iCurrState == INT_SERVER_WORKING )
      *// retrieving next action*
      iCount = oSel.select();
      if ( iCount > 0 )
      oItSelKeys = oSel.selectedKeys().iterator();
      while ( oItSelKeys.hasNext() )
      oSelKey = oItSelKeys.next();
      if ( oSelKey.isValid() )
      switch ( oSelKey.readyOps() & iMask ) {
      case SelectionKey.OP_ACCEPT :
      oSockChan = oSSockChan.accept();
      oSock = oSockChan.socket();
      oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
      case SelectionKey.OP_READ :
      ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
      this.getReader().add(oSelKey); *// sending key to reading thread*
      case SelectionKey.OP_WRITE :
      ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
      this.getWriter().add(oSelKey); *// sending key to writing thread*
      case SelectionKey.OP_CONNECT :
      default :
      *// nothing to do*
      catch ( IOException oExcept )
      *// do some actions*

      Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
      But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!

      Please help with idea how can I terminate such connections!