Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

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

985408Jan 17 2013 — edited Jan 18 2013
Hello.
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:

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

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!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 15 2013
Added on Jan 17 2013
7 comments
4,735 views