/** * @param selector The selector. * @param server The server socket channel. * @param now The current time. * @throws IOException Any IOException. */ @Override protected void doAccept(final Selector selector, ServerSocketChannel server, long now) throws IOException { logger.debug("New accept"); SocketChannel channel = server.accept(); if (isShuttingDown()) { if (logger.isInfoEnabled()) { logger.info( "New connection from " + channel.socket().getInetAddress().getHostAddress() + " rejected; the server is in the process of shutting down."); } channel.close(); } else { try { channel.configureBlocking(false); Socket socket = channel.socket(); setSocketAttributes(socket); TcpNioConnection connection = createTcpNioConnection(channel); if (connection == null) { return; } connection.setTaskExecutor(getTaskExecutor()); connection.setLastRead(now); this.channelMap.put(channel, connection); channel.register(selector, SelectionKey.OP_READ, connection); connection.publishConnectionOpenEvent(); } catch (Exception e) { logger.error("Exception accepting new connection", e); channel.close(); } } }
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); try { InetAddress lh = InetAddress.getLocalHost(); int port = ((InetSocketAddress) (ssc.getLocalAddress())).getPort(); SocketAddress remote = new InetSocketAddress(lh, port); // Test SocketChannel shutdownXXX SocketChannel sc; sc = SocketChannel.open(remote); try { acceptAndReset(ssc); sc.shutdownInput(); sc.shutdownOutput(); } finally { sc.close(); } // Test Socket adapter shutdownXXX and isShutdownInput sc = SocketChannel.open(remote); try { acceptAndReset(ssc); boolean before = sc.socket().isInputShutdown(); sc.socket().shutdownInput(); boolean after = sc.socket().isInputShutdown(); if (before || !after) throw new RuntimeException("Before and after test failed"); sc.socket().shutdownOutput(); } finally { sc.close(); } } finally { ssc.close(); } }
void add(Target t) { SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); boolean connected = sc.connect(t.address); t.channel = sc; t.connectStart = System.currentTimeMillis(); if (connected) { t.connectFinish = t.connectStart; sc.close(); printer.add(t); } else { synchronized (pending) { pending.add(t); } sel.wakeup(); } } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) { } } t.failure = x; printer.add(t); } }
// Process keys that have become selected // void processSelectedKeys() throws IOException { for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) { // Retrieve the next key and remove it from the set SelectionKey sk = (SelectionKey) i.next(); i.remove(); // Retrieve the target and the channel Target t = (Target) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); // Attempt to complete the connection sequence try { if (sc.finishConnect()) { sk.cancel(); t.connectFinish = System.currentTimeMillis(); sc.close(); printer.add(t); } } catch (IOException x) { sc.close(); t.failure = x; printer.add(t); } } }
/* ------------------------------------------------------------ */ public void startConnection(HttpDestination destination) throws IOException { SocketChannel channel = null; try { channel = SocketChannel.open(); Address address = destination.isProxied() ? destination.getProxy() : destination.getAddress(); channel.socket().setTcpNoDelay(true); if (_httpClient.isConnectBlocking()) { channel.socket().connect(address.toSocketAddress(), _httpClient.getConnectTimeout()); channel.configureBlocking(false); _selectorManager.register(channel, destination); } else { channel.configureBlocking(false); channel.connect(address.toSocketAddress()); _selectorManager.register(channel, destination); ConnectTimeout connectTimeout = new ConnectTimeout(channel, destination); _httpClient.schedule(connectTimeout, _httpClient.getConnectTimeout()); _connectingChannels.put(channel, connectTimeout); } } catch (UnresolvedAddressException ex) { if (channel != null) channel.close(); destination.onConnectionFailed(ex); } catch (IOException ex) { if (channel != null) channel.close(); destination.onConnectionFailed(ex); } }
public byte[] handleRead() throws IOException { boolean find = false; int index = 0; if (state == READING_LENGTH) { int nbread = sock.read(lenBuf); if (nbread == -1) { // Error of reading bytes, so close the socket to prevent other error sock.close(); connectionClosed = true; return null; } if (lenBuf.remaining() == 0) { // Read the length int length = Util.readInt32(lenBuf.array(), 0); int size = buffers.size(); for (int i = 0; i < size; i++) { if (buffers.get(i).capacity() == length) { find = true; index = i; } } if (find) { msgBuf = buffers.get(index); // System.out.println("buffer with a right size found"); } else { try { msgBuf = ByteBuffer.allocate(length); buffers.add(msgBuf); } catch (OutOfMemoryError e) { System.err.println(e); sock.close(); connectionClosed = true; return null; } // System.out.println("No buffer found : length : " + length); } msgBuf.clear(); lenBuf = (ByteBuffer) lenBuf.position(0); state = READING_MSG; } } if (state == READING_MSG) { sock.read(msgBuf); if (msgBuf.remaining() == 0) { // the message has been fully received // deliver it" byte[] msg = msgBuf.array(); state = READING_LENGTH; return msg; } } return null; }
static void test() throws Exception { ServerSocketChannel ssc = null; SocketChannel sc = null; SocketChannel peer = null; try { ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); // loopback connection InetAddress lh = InetAddress.getLocalHost(); sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort())); peer = ssc.accept(); // peer sends message so that "sc" will be readable int n = peer.write(ByteBuffer.wrap("Hello".getBytes())); assert n > 0; sc.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); boolean done = false; int failCount = 0; while (!done) { int nSelected = selector.select(); if (nSelected > 0) { if (nSelected > 1) throw new RuntimeException("More than one channel selected"); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { key = iterator.next(); iterator.remove(); if (key.isWritable()) { failCount++; if (failCount > 10) throw new RuntimeException("Test failed"); Thread.sleep(250); } if (key.isReadable()) { done = true; } } } } } finally { if (peer != null) peer.close(); if (sc != null) sc.close(); if (ssc != null) ssc.close(); } }
@Override public Void call() throws Exception { ServerSocketChannel clientConnection = (ServerSocketChannel) selectionKey.channel(); SocketChannel channel = clientConnection.accept(); if (channel != null) { channel.configureBlocking(false); LOGGER.info( String.format("%s accepted client connection from %s", name, channel.getRemoteAddress())); try { final HttpRequest.HttpRequestWrapper requestWrapper = requestParser.parse(read(channel)); MethodHandler handler = RequestHandlerFactory.newInstance(requestWrapper.getRequestLine().getMethod()); HttpResponse.HttpResponseWrapper responseWrapper = handler.handle(requestWrapper); write(channel, responseWrapper); } finally { channel.close(); } LOGGER.info(String.format("%s is done.", name)); } return null; }
private void listen() throws IOException { while (true) { int selec = selector.select(500); if (selec == 0) { continue; } Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); try { iterator.remove(); if (selectionKey.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } else if (selectionKey.isReadable()) { read(selectionKey); } else if (selectionKey.isWritable()) { write(selectionKey); } } catch (Exception e) { // iterator.remove(); Don't use it! It can throw a exception! SocketChannel sc = (SocketChannel) selectionKey.channel(); sc.close(); } } } }
public void writeResponsePacket(SocketChannel socketChannel, ResponsePacket responsePacket) { try { ByteBuffer byteBuffer; byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] marshalObject = MarshalHelper.objectToBytes(responsePacket); byte[] marshalHeader = MarshalHelper.int32ToBytes(marshalObject.length); byteBuffer.clear(); byteBuffer.put(marshalHeader); byteBuffer.put(marshalObject); byteBuffer.flip(); // If no connection now, please ignore it (usually in async calling) try { if (socketChannel.isConnected()) { socketChannel.write(byteBuffer); } } catch (IOException e) { socketChannel.close(); } } catch (IOException e) { e.printStackTrace(); } }
private void read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); // Clear out our read buffer so it's ready for new data readBuffer.clear(); // Attempt to read off the channel int numRead; try { numRead = socketChannel.read(readBuffer); } catch (IOException e) { key.cancel(); socketChannel.close(); System.out.println("Forceful shutdown"); return; } if (numRead == -1) { System.out.println("Graceful shutdown"); key.channel().close(); key.cancel(); return; } socketChannel.register(selector, SelectionKey.OP_WRITE); numMessages++; if (numMessages % 100000 == 0) { long elapsed = System.currentTimeMillis() - loopTime; loopTime = System.currentTimeMillis(); System.out.println(elapsed); } }
// Called when a peer we're trying to connect to sends us a message private void processNewPeer(SocketChannel c) throws IOException { ByteBuffer message = ChannelHelper.readBytes(c, 4); String recognize = utf8.decode(message).toString(); if (!recognize.equals("bam!")) { // Connected to something that wasn't a BAMPong client... c.close(); Peer p = new_peers.remove(c); log("Closing attempt to " + p.getName() + " got " + recognize); return; } // Assemble response ByteBuffer name = utf8.encode(nick); message = ByteBuffer.allocateDirect(name.limit() + 10); // id(4), port(4), name(2+limit) message.putInt(id); message.putInt(getPort()); ChannelHelper.putString(message, name); message.flip(); // Send message c.write(message); // Move socket to connected peers. Peer peer = new_peers.remove(c); peers.put(c, peer); sockets.put(peer, c); }
boolean initiateConnection(Connection conn_, Peer peer) { TCPConnection conn = (TCPConnection) conn_; try { SocketChannel channel = SocketChannel.open(); InetSocketAddress localAddress = new InetSocketAddress(conn.host_id, 0); channel.socket().bind(localAddress); channel.configureBlocking(false); try { InetSocketAddress remoteAddress = new InetSocketAddress(peer.host(), peer.port()); if (channel.connect(remoteAddress)) { // This only happens on Solaris when connecting locally logger.log(Level.FINEST, "Connected!"); conn.state = Connection.State.connected_out; conn.channel = channel; selector.wakeup(); channel.register(selector, SelectionKey.OP_READ, conn); initiateCER(conn); return true; } } catch (java.nio.channels.UnresolvedAddressException ex) { channel.close(); return false; } conn.state = Connection.State.connecting; conn.channel = channel; selector.wakeup(); channel.register(selector, SelectionKey.OP_CONNECT, conn); } catch (java.io.IOException ex) { logger.log( Level.WARNING, "java.io.IOException caught while initiating connection to '" + peer.host() + "'.", ex); } return true; }
/** Closes the underlying sockets and socket streams. */ @Override public void close() throws IOException { SocketChannel s = _s; _s = null; if (s != null) { s.close(); } /* OutputStream os = _os; _os = null; InputStream is = _is; _is = null; try { if (os != null) os.close(); if (is != null) is.close(); } finally { if (s != null) s.close(); } */ }
private void handleInput(SelectionKey key) throws IOException { if (key != null && key.isValid()) { SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); doWrite(sc); } else System.exit(1); } if (key.isReadable()) { ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { key.cancel(); sc.close(); } else { } } } }
private void close(SelectionKey key) { try { RapidoidConnection conn = (RapidoidConnection) key.attachment(); if (key.isValid()) { SocketChannel socketChannel = (SocketChannel) key.channel(); socketChannel.close(); key.attach(null); key.cancel(); } if (conn != null) { if (!conn.closed) { U.trace("Closing connection", "connection", conn); conn.closed = true; assert conn.key == key; conn.key = null; connections.release(conn); } } } catch (IOException e) { e.printStackTrace(); } }
/** * Handle received selection keys. * * @param selectionKeys the selection keys. * @throws IOException */ private void handleSelectionKeys(Set<SelectionKey> selectionKeys) throws IOException { if (CollectionUtils.isEmpty(selectionKeys)) { // nothing happened return; } int size = selectionKeys.size(); this.logger.info("Handling [{}] selection keys", size); // something happened Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); this.logger.debug("Remaining [{}] selection keys", selectionKeys.size()); // remove as to not process again. try { if (!selectionKey.isValid()) { continue; } SelectionKeyCommand selectionKeyCommand = this.selectionKeyCommandFactory.getSelectionKeyCommand(selectionKey); selectionKeyCommand.execute(selectionKey); } catch (Exception ex) { StringBuffer buffer = new StringBuffer("Error ["); buffer.append(ex.getMessage()); buffer.append("] on ["); buffer.append(selectionKey.channel()); buffer.append("] channel"); this.logger.error(buffer.toString(), ex); SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); socketChannel.close(); } } this.logger.info("Handled [{}] selection keys", size); }
/** * ���һ��Socketͨ�������Ը�ͨ����һЩ��ʼ���Ĺ��� * * @param ip ���ӵķ�������ip * @param port ���ӵķ������Ķ˿ں� * @throws IOException */ public void initClient(String ip, int port) { // ���һ��Socketͨ�� SocketChannel channel = null; try { channel = SocketChannel.open(); // ����ͨ��Ϊ������ channel.configureBlocking(false); // ���һ��ͨ�������� this.selector = Selector.open(); // �ͻ������ӷ�����,��ʵ����ִ�в�û��ʵ�����ӣ���Ҫ��listen���������е� // ��channel.finishConnect();����������� channel.connect(new InetSocketAddress(ip, port)); // ��ͨ����������ͨ������Ϊ��ͨ��ע��SelectionKey.OP_CONNECT�¼��� channel.register(selector, SelectionKey.OP_CONNECT); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); if (channel != null) { try { channel.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
public void run() { // TODO Auto-generated method stub ServerSocketChannel server = null; try { server = ServerSocketChannel.open(); logger.debug("Trying to bind on port - " + port); server.socket().bind(new InetSocketAddress(port)); } catch (Exception e) { logger.error(e.getMessage(), e); return; } while (true) { SocketChannel client = null; try { client = server.accept(); IRequestHandler handler = factory.create(client, LoadBalancer.getInstance().get(), this); handler.setId(counter++); requests.add(handler); setChanged(); notifyObservers(handler); } catch (IOException e) { try { if (client != null) client.close(); } catch (IOException ee) { logger.error(ee.getMessage(), ee); } logger.error(e.getMessage(), e); } } }
/** * Create a new socket to the data port and send a block request. The returned value is the * response from the server. */ private DataServerMessage request(final BlockInfo block, final long offset, final long length) throws IOException, TException { DataServerMessage sendMsg = DataServerMessage.createBlockRequestMessage(block.blockId, offset, length); SocketChannel socketChannel = SocketChannel.open( new InetSocketAddress( block.getLocations().get(0).getWorkerAddress().getHost(), block.getLocations().get(0).getWorkerAddress().getDataPort())); try { while (!sendMsg.finishSending()) { sendMsg.send(socketChannel); } DataServerMessage recvMsg = DataServerMessage.createBlockResponseMessage(false, block.blockId, offset, length, null); while (!recvMsg.isMessageReady()) { int numRead = recvMsg.recv(socketChannel); if (numRead == -1) { break; } } return recvMsg; } finally { socketChannel.close(); } }
@Override public void newConnection(Multiplexer multiplexer, SocketChannel socket) throws Exception { switch (_role) { case Sender: multiplexer.add(new Sender(socket)); break; case Receiver: /* From the GridFTP 2 spec: "After receiving EOF block * from a sender host, active data receiver host must not * try to open any new data channels to that sender host." * * This rule is difficult to honor, as we may have a * connection establishment "in progress" at the time we * received the EOF. At the same time it is not clear if * an active receiver is allowed to close a connection * before READY has been sent; passive receivers are * explicitly allowed to do so. */ if (_eof) { socket.close(); } else { multiplexer.add(new Receiver(socket)); } break; } }
protected void closeSocketChannel(SocketChannel socketChannel, FileDescriptor fileDescriptor) throws IOException { ReflectionTestUtil.setFieldValue(socketChannel, "fd", fileDescriptor); socketChannel.close(); }
/** * Test of a large write on a socket to understand what happens when the write is greater than the * combined size of the client send buffer and the server receive buffer and the server side of * the socket is either not accepted or already shutdown. * * @throws IOException * @throws InterruptedException */ public void testDirectSockets_largeWrite_NotAccepted() throws IOException, InterruptedException { final Random r = new Random(); // Get a socket addresss for an unused port. final InetSocketAddress serverAddr = new InetSocketAddress(getPort(0)); // First our ServerSocket final ServerSocket ss = new ServerSocket(); try { // Size of the server socket receive buffer. final int receiveBufferSize = ss.getReceiveBufferSize(); // Allocate buffer twice as large as the receive buffer. final byte[] largeBuffer = new byte[receiveBufferSize * 10]; if (log.isInfoEnabled()) { log.info( "receiveBufferSize=" + receiveBufferSize + ", largeBufferSize=" + largeBuffer.length); } // fill buffer with random data. r.nextBytes(largeBuffer); // bind the ServerSocket to the specified port. ss.bind(serverAddr); // Now the first Client SocketChannel final SocketChannel cs = SocketChannel.open(); try { /* * Note: true if connection made. false if connection in * progress. */ final boolean immediate = cs.connect(serverAddr); if (!immediate) { // Did not connect immediately, so finish connect now. if (!cs.finishConnect()) { fail("Did not connect."); } } /* * Attempt to write data. The server socket is not yet accepted. * This should hit a timeout. */ assertTimeout(10L, TimeUnit.SECONDS, new WriteBufferTask(cs, ByteBuffer.wrap(largeBuffer))); accept(ss); } finally { cs.close(); } } finally { ss.close(); } }
public String connect(final String ipAddress, final int port) { for (int i = 0; i <= _retry; i++) { SocketChannel sch = null; try { if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to connect to " + ipAddress); } sch = SocketChannel.open(); sch.configureBlocking(true); final InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; } catch (final IOException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Could not connect to " + ipAddress); } } finally { if (sch != null) { try { sch.close(); } catch (final IOException e) { } } } try { Thread.sleep(_sleep); } catch (final InterruptedException e) { } } s_logger.debug("Unable to logon to " + ipAddress); return "Unable to connect"; }
private void doClose(Context cx, Function callback) { super.close(); try { ScriptRunner runner = getRunner(); if (clientChannel != null) { if (log.isDebugEnabled()) { log.debug("Closing client channel {}", clientChannel); } clientChannel.close(); runner.unregisterCloseable(clientChannel); } if (svrChannel != null) { if (log.isDebugEnabled()) { log.debug("Closing server channel {}", svrChannel); } svrChannel.close(); runner.unregisterCloseable(svrChannel); } if (callback != null) { runner.enqueueCallback(callback, this, null, runner.getDomain(), new Object[] {}); } } catch (IOException ioe) { log.debug("Uncaught exception in channel close: {}", ioe); setErrno(Constants.EIO); } }
public static void main(String[] args) throws IOException, InterruptedException { String nic = args.length > 0 ? args[0] : "0.0.0.0"; int port = args.length > 1 ? Integer.parseInt(args[1]) : 12345; System.out.println("Listening on interface : " + nic + ":" + port); final ByteBuffer buffy = ByteBuffer.allocateDirect(PAGE_SIZE).order(ByteOrder.nativeOrder()); final ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(nic, port)); SocketChannel accepted = null; try { accepted = serverSocket.accept(); accepted.socket().setTcpNoDelay(true); accepted.configureBlocking(false); serverSocket.close(); Selector selector = Selector.open(); accepted.register(selector, SelectionKey.OP_READ); while (!Thread.interrupted()) { if (pong(buffy, accepted, selector)) return; } } finally { if (accepted != null) { try { accepted.close(); } catch (IOException ignored) { } } } }
/** * Called when a new connection is pending on the underlying {@link ServerSocketChannel}. * * @param key The {@link SelectionKey} for the socket on which a connection is pending. * @throws IOException if an error occurs while accepting the new connection. */ protected void accept(SelectionKey key) throws IOException { // Pull out the socket channel that has a connection pending ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // Accept the connection SocketChannel socketChannel = serverSocketChannel.accept(); Socket socket = socketChannel.socket(); // Check if our AcceptPolicy will allow this new connection if (this.acceptPolicy != null && !this.acceptPolicy.shouldRetain(socketChannel, this.getSocketSelector().keys().size())) { if (log.logTrace()) { log.trace("Closing accepted connection (accept policy enforced)"); } socketChannel.close(); return; } this.registerChannel(socketChannel); // Register the new socket. This will promote it to an SSLSocket // if we're configured for HTTPS. this.registerSocket(socket, this.host, this.port, false); // Add the new SocketChannel to our Selector socketChannel.configureBlocking(false); SelectionKey acceptKey = socketChannel.register(this.getSocketSelector(), SelectionKey.OP_READ); this.resetClientTimer(socketChannel.socket()); }
private void read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); // Clear out our read buffer so it's ready for new data this.readBuffer.clear(); // Attempt to read off the channel int numRead; try { numRead = socketChannel.read(this.readBuffer); } catch (IOException e) { // The remote forcibly closed the connection, cancel // the selection key and close the channel. key.cancel(); socketChannel.close(); return; } if (numRead == -1) { // Remote entity shut the socket down cleanly. Do the // same from our end and cancel the channel. key.channel().close(); key.cancel(); return; } // Hand the data off to our worker thread this.worker.processData(this, socketChannel, this.readBuffer.array(), numRead); }
@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); } } } }
public void addTarget(Target target) { // 向targets队列中加入一个任务 SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(target.address); target.channel = socketChannel; target.connectStart = System.currentTimeMillis(); synchronized (targets) { targets.add(target); } selector.wakeup(); } catch (Exception x) { if (socketChannel != null) { try { socketChannel.close(); } catch (IOException xx) { } } target.failure = x; addFinishedTarget(target); } }