public void listen(int backlog, NetworkHandleListener listener, Object context)
throws NodeOSException
{
if (boundAddress == null) {
throw new NodeOSException(Constants.EINVAL);
}
NetworkPolicy netPolicy = getNetworkPolicy();
if ((netPolicy != null) && !netPolicy.allowListening(boundAddress)) {
log.debug("Address {} not allowed by network policy", boundAddress);
throw new NodeOSException(Constants.EINVAL);
}
this.listener = listener;
this.listenerCtx = context;
if (log.isDebugEnabled()) {
log.debug("Server listening on {} with backlog {}",
boundAddress, backlog);
}
boolean success = false;
try {
svrChannel = ServerSocketChannel.open();
runtime.registerCloseable(svrChannel);
svrChannel.configureBlocking(false);
svrChannel.socket().setReuseAddress(true);
svrChannel.socket().bind(boundAddress, backlog);
svrChannel.register(runtime.getSelector(), SelectionKey.OP_ACCEPT,
new SelectorHandler()
{
@Override
public void selected(SelectionKey key)
{
serverSelected(key);
}
});
success = true;
} catch (BindException be) {
log.debug("Error listening: {}", be);
throw new NodeOSException(Constants.EADDRINUSE);
} catch (IOException ioe) {
log.debug("Error listening: {}", ioe);
throw new NodeOSException(Constants.EIO);
} finally {
if (!success && (svrChannel != null)) {
runtime.unregisterCloseable(svrChannel);
try {
svrChannel.close();