in commons-jcs3-core/src/main/java/org/apache/commons/jcs3/auxiliary/lateral/socket/tcp/LateralTCPListener.java [519:603]
private void runListener(final ServerSocketChannel serverSocket)
{
try (Selector selector = Selector.open())
{
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
log.debug("Waiting for clients to connect");
// Check to see if we've been asked to exit, and exit
while (!terminated.get())
{
final int activeKeys = selector.select(acceptTimeOut);
if (activeKeys == 0)
{
continue;
}
for (final Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();)
{
if (terminated.get())
{
break;
}
final SelectionKey key = i.next();
if (!key.isValid())
{
continue;
}
if (key.isAcceptable())
{
final ServerSocketChannel server = (ServerSocketChannel) key.channel();
final SocketChannel client = server.accept();
if (client == null)
{
//may happen in non-blocking mode
continue;
}
log.info("Connected to client at {0}", client.getRemoteAddress());
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
if (key.isReadable())
{
handleClient(key);
}
i.remove();
}
}
log.debug("Thread terminated, exiting gracefully");
//close all registered channels
selector.keys().forEach(key -> {
try
{
key.channel().close();
}
catch (final IOException e)
{
log.warn("Problem closing channel", e);
}
});
}
catch (final IOException e)
{
log.error( "Exception caught in TCP listener", e );
}
finally
{
try
{
serverSocket.close();
}
catch (final IOException e)
{
log.error( "Exception closing TCP listener", e );
}
}
}