@JSFunction public static Object connect(Context cx, Scriptable thisObj, Object[] args, Function func) { final TCPImpl tcp = (TCPImpl) thisObj; String host = stringArg(args, 0); int port = intArg(args, 1); boolean success = false; SocketChannel newChannel = null; try { InetSocketAddress targetAddress = new InetSocketAddress(host, port); NetworkPolicy netPolicy = tcp.getNetworkPolicy(); if ((netPolicy != null) && !netPolicy.allowConnection(targetAddress)) { log.debug("Disallowed connection to {} due to network policy", targetAddress); setErrno(Constants.EINVAL); return null; } if (log.isDebugEnabled()) { log.debug("Client connecting to {}:{}", host, port); } clearErrno(); if (tcp.boundAddress == null) { newChannel = SocketChannel.open(); } else { newChannel = SocketChannel.open(tcp.boundAddress); } tcp.clientChannel = newChannel; getRunner().registerCloseable(newChannel); tcp.clientInit(); tcp.clientChannel.connect(targetAddress); tcp.selKey = tcp.clientChannel.register( getRunner().getSelector(), SelectionKey.OP_CONNECT, new SelectorHandler() { @Override public void selected(SelectionKey key) { tcp.clientSelected(key); } }); tcp.pendingConnect = (PendingOp) cx.newObject(thisObj, PendingOp.CLASS_NAME); success = true; return tcp.pendingConnect; } catch (IOException ioe) { log.debug("Error on connect: {}", ioe); setErrno(Constants.EIO); return null; } finally { if (!success && (newChannel != null)) { getRunner().unregisterCloseable(newChannel); try { newChannel.close(); } catch (IOException ioe) { log.debug("Error closing channel that might be closed: {}", ioe); } } } }