Java Code Examples for java.nio.channels.SelectionKey#isConnectable()
The following examples show how to use
java.nio.channels.SelectionKey#isConnectable() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PassiveRedisIndexer.java From mldht with Mozilla Public License 2.0 | 6 votes |
@Override public void selectionEvent(SelectionKey key) throws IOException { if(key.isValid() && key.isConnectable()) { chan.finishConnect(); conMan.interestOpsChanged(this); } if(key.isValid() && key.isReadable()) read(); if(key.isValid() && key.isWritable()) { awaitingWriteNotification = false; tryWrite.run(); conMan.interestOpsChanged(this); } }
Example 2
Source File: PassiveRedisIndexer.java From bt with Apache License 2.0 | 6 votes |
@Override public void selectionEvent(SelectionKey key) throws IOException { if(key.isValid() && key.isConnectable()) { chan.finishConnect(); conMan.interestOpsChanged(this); } if(key.isValid() && key.isReadable()) read(); if(key.isValid() && key.isWritable()) { awaitingWriteNotification = false; tryWrite.run(); conMan.interestOpsChanged(this); } }
Example 3
Source File: ChannelManagerImpl.java From xenqtt with Apache License 2.0 | 6 votes |
private void doConnect(long now, Set<SelectionKey> keys) { Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); try { if (key.isConnectable()) { MqttChannel channel = (MqttChannel) key.attachment(); if (!channel.finishConnect()) { channelClosed(channel); iter.remove(); } } } catch (CancelledKeyException e) { iter.remove(); } } }
Example 4
Source File: NIOConnector.java From heisenberg with Apache License 2.0 | 6 votes |
@Override public void run() { final Selector selector = this.selector; for (;;) { ++connectCount; try { selector.select(1000L); connect(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid() && key.isConnectable()) { finishConnect(key, att); } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
Example 5
Source File: CULNetworkHandlerImpl.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
private void processSelectedKeys(Set<SelectionKey> keys) throws Exception { Iterator<SelectionKey> itr = keys.iterator(); while (itr.hasNext()) { SelectionKey key = itr.next(); if (key.isReadable()) { processRead(key); } if (key.isWritable()) { processWrite(key); } if (key.isConnectable()) { processConnect(key); } if (key.isAcceptable()) { ; } itr.remove(); } }
Example 6
Source File: NonBlockingFetcher.java From SEAL with Apache License 2.0 | 5 votes |
private static void processKeys() { Set<SelectionKey> keys = selector.selectedKeys(); for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) { SelectionKey key = iter.next(); iter.remove(); Work work = (Work) key.attachment(); SocketChannel channel = (SocketChannel) key.channel(); try { // If timed out if (System.currentTimeMillis() - startTime > timeout) { finished(channel, key, work); continue; } if (key.isConnectable() && channel.finishConnect()) { // If the Channel is connected, setup the Channel to // write the HTTP message to the remote server key.interestOps(SelectionKey.OP_WRITE); } else if (key.isWritable()) { // If the Channel is finished writing, setup the // Channel to read the HTTP response if (doWrite(channel, work)) key.interestOps(SelectionKey.OP_READ); } else if (key.isReadable()) { // If the Channel is finished reading, call finished // to complete the work if (doRead(channel, work)) finished(channel, key, work); } } catch (IOException ioe) { log.error("Failure during IO operation"); finished(channel, key, work); } } }
Example 7
Source File: PullMetaDataConnection.java From bt with Apache License 2.0 | 5 votes |
@Override public void selectionEvent(SelectionKey key) throws IOException { if(key.isValid() && key.isConnectable()) connectEvent(); if(key.isValid() && key.isReadable()) canReadEvent(); if(key.isValid() && key.isWritable()) canWriteEvent(); }
Example 8
Source File: PullMetaDataConnection.java From mldht with Mozilla Public License 2.0 | 5 votes |
@Override public void selectionEvent(SelectionKey key) throws IOException { if(key.isValid() && key.isConnectable()) connectEvent(); if(key.isValid() && key.isReadable()) canReadEvent(); if(key.isValid() && key.isWritable()) canWriteEvent(); }
Example 9
Source File: TestMessageIO.java From tracing-framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static boolean awaitOp(Selector selector, SelectionKey key, int op) throws IOException { long end = System.currentTimeMillis() + SELECTION_TIMEOUT_MS; boolean selected = false; while (!selected) { // Check timeout long remaining = end - System.currentTimeMillis(); if (remaining < 0) { break; } // Select up to remaining millis selector.select(remaining); // Handle op if possible switch (op) { case SelectionKey.OP_READ: selected |= key.isReadable(); break; case SelectionKey.OP_ACCEPT: selected |= key.isAcceptable(); break; case SelectionKey.OP_WRITE: selected |= key.isWritable(); break; case SelectionKey.OP_CONNECT: selected |= key.isConnectable(); break; } } return selected; }
Example 10
Source File: Progress.java From twister2 with Apache License 2.0 | 5 votes |
private void handleSelectedKeys() { Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); SelectHandler callback = (SelectHandler) key.attachment(); if (!key.isValid()) { callback.handleError(key.channel()); continue; } if (key.isValid() && key.isWritable()) { callback.handleWrite(key.channel()); } if (key.isValid() && key.isReadable()) { callback.handleRead(key.channel()); } if (key.isValid() && key.isConnectable()) { callback.handleConnect(key.channel()); } if (key.isValid() && key.isAcceptable()) { callback.handleAccept(key.channel()); } } }
Example 11
Source File: NioClientManager.java From bitherj with Apache License 2.0 | 5 votes |
private void handleKey(SelectionKey key) throws IOException { // We could have a !isValid() key here if the connection is already closed at this point if (key.isValid() && key.isConnectable()) { // ie a client connection which has finished // the initial connect process // Create a ConnectionHandler and hook everything together StreamParser parser = (StreamParser) key.attachment(); SocketChannel sc = (SocketChannel) key.channel(); ConnectionHandler handler = new ConnectionHandler(parser, key, connectedHandlers); try { if (sc.finishConnect()) { log.info("Successfully connected to {}", sc.socket().getRemoteSocketAddress()); key.interestOps(SelectionKey.OP_READ).attach(handler); handler.parser.connectionOpened(); } else { log.error("Failed to connect to {}", sc.socket().getRemoteSocketAddress()); handler.closeConnection(); // Failed to connect for some reason } } catch (Exception e) { // If e is a CancelledKeyException, there is a race to get to interestOps after // finishConnect() which // may cause this. Otherwise it may be any arbitrary kind of connection failure. // Calling sc.socket().getRemoteSocketAddress() here throws an exception, // so we can only log the error itself handler.closeConnection(); } } else if (key.isValid()) // Process bytes read { ConnectionHandler.handleKey(key); } }
Example 12
Source File: NIOConnector.java From Mycat-NIO with Apache License 2.0 | 5 votes |
@Override public void run() { final Selector selector = this.selector; for (;;) { ++connectCount; try { selector.select(1000L); connect(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid() && key.isConnectable()) { finishConnect(key, att); } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
Example 13
Source File: TimeClientHandler.java From JavaInterview with Apache License 2.0 | 5 votes |
private void handleDataFromServer(SelectionKey key) throws IOException { if (key.isValid()) { SocketChannel sc = (SocketChannel) key.channel(); //判断先前是否连接成功,如果构造器里面的socketChannel已经连接成功了, // 则此处不会有connectable的操作select到 if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(this.selector, SelectionKey.OP_READ); doWrite(sc); } else { //连接失败,程序退出 System.out.println("connect failed!!!"); System.exit(-1); } } // read the data from server if (key.isReadable()) { ByteBuffer readBuf = ByteBuffer.allocate(1024); int readByteLen = sc.read(readBuf); if (readByteLen > 0) { readBuf.flip(); byte[] readBytes = new byte[readBuf.remaining()]; readBuf.get(readBytes); String body = new String(readBytes, "UTF-8"); System.out.println("Now is:" + body); this.stop = true; } } } }
Example 14
Source File: NioTcpClient.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
public void processReadyKey(SelectionKey key) { if (key.isValid()) if (key.isConnectable()) { processConnect(key); } else { if (key.isWritable()) { processWrite(key); } if (key.isReadable()) { processRead(); } } }
Example 15
Source File: Reactor.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void dispatchEvent(final SelectionKey key) throws IOException { if (key.isConnectable()) { acceptor.handleConnectEvent(key); } else if (key.isAcceptable()) { acceptor.handleAcceptEvent(key); } else if (key.isReadable()) { acceptor.handleReadEvent(key); } else if (key.isValid() && key.isWritable()) { acceptor.handleWriteEvent(key); } }
Example 16
Source File: OioSctpChannel.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { if (localAddress != null) { ch.bind(localAddress); } boolean success = false; try { ch.connect(remoteAddress); boolean finishConnect = false; while (!finishConnect) { if (connectSelector.select(SO_TIMEOUT) >= 0) { final Set<SelectionKey> selectionKeys = connectSelector.selectedKeys(); for (SelectionKey key : selectionKeys) { if (key.isConnectable()) { selectionKeys.clear(); finishConnect = true; break; } } selectionKeys.clear(); } } success = ch.finishConnect(); } finally { if (!success) { doClose(); } } }
Example 17
Source File: OioSctpChannel.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { if (localAddress != null) { ch.bind(localAddress); } boolean success = false; try { ch.connect(remoteAddress); boolean finishConnect = false; while (!finishConnect) { if (connectSelector.select(SO_TIMEOUT) >= 0) { final Set<SelectionKey> selectionKeys = connectSelector.selectedKeys(); for (SelectionKey key : selectionKeys) { if (key.isConnectable()) { selectionKeys.clear(); finishConnect = true; break; } } selectionKeys.clear(); } } success = ch.finishConnect(); } finally { if (!success) { doClose(); } } }
Example 18
Source File: NioSelectorLoop.java From TakinRPC with Apache License 2.0 | 4 votes |
@Override public void run() { while (running) { try { select(); Set<SelectionKey> selectionKeys = selector.selectedKeys(); if (selectionKeys.isEmpty()) { continue; } Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { final SelectionKey key = iterator.next(); iterator.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key); } if (key.isConnectable()) { doConnect(key); } if (key.isValid() && key.isReadable()) { doRead(key); } if (key.isValid() && key.isWritable()) { doWrite(key); } } } catch (Throwable t) { LOGGER.warn("Unexpected exception in the selector loop.", t); // 睡眠1S, 防止连续的异常导致cpu消耗 try { Thread.sleep(1000); } catch (InterruptedException ignore) { } } } }
Example 19
Source File: NIOServer.java From JavaBase with MIT License | 4 votes |
private void start() throws Exception { Selector selector = Selector.open(); //通过OPEN方法来打开一个未绑定的ServerSocketChannel 实例 ServerSocketChannel server = ServerSocketChannel.open(); //将该ServerSocketChannel绑定到指定 ip 端口 server.bind(new InetSocketAddress(PORT)); //设置是NIO 非阻塞模式 server.configureBlocking(false); //将sever注册到指定Selector对象上 server.register(selector, SelectionKey.OP_ACCEPT); while (!stop) { // 因为只有在选择了至少一个通道后,才会返回该选择器的唤醒方法,或者当前线程中断,以先到者为准。否则一直阻塞 selector.select(); //依次处理selector上的每个已经准备好的管道 Set<SelectionKey> selectedKeys = selector.selectedKeys(); for (SelectionKey sk : selectedKeys) { //从selector上的已选择key集 中删除正在处理的连接请求 selector.selectedKeys().remove(sk); // 连接 accept if (sk.isAcceptable()) { register(selector, server, sk); } // 连接建立 else if (sk.isConnectable()) { System.out.println("close"); } // 读就绪 else if (sk.isReadable()) { readContent(selector, sk); } // 写就绪 else if (sk.isWritable()) { } } } }
Example 20
Source File: Transfer.java From nitroshare-android with MIT License | 4 votes |
/** * Perform the transfer until it completes or an error occurs */ @Override public void run() { try { // Indicate which operations select() should select for SelectionKey selectionKey = mSocketChannel.register( mSelector, mTransferStatus.getDirection() == TransferStatus.Direction.Receive ? SelectionKey.OP_READ : SelectionKey.OP_CONNECT ); // For a sending transfer, connect to the remote device if (mTransferStatus.getDirection() == TransferStatus.Direction.Send) { mSocketChannel.connect(new InetSocketAddress(mDevice.getHost(), mDevice.getPort())); } while (true) { mSelector.select(); if (mStop) { break; } if (selectionKey.isConnectable()) { mSocketChannel.finishConnect(); selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); synchronized (mTransferStatus) { mTransferStatus.setState(TransferStatus.State.Transferring); notifyStatusChangedListeners(); } } if (selectionKey.isReadable()) { if (!processNextPacket()) { if (mTransferStatus.getDirection() == TransferStatus.Direction.Receive) { selectionKey.interestOps(SelectionKey.OP_WRITE); } else { break; } } } if (selectionKey.isWritable()) { if (!sendNextPacket()) { if (mTransferStatus.getDirection() == TransferStatus.Direction.Receive) { break; } else { selectionKey.interestOps(SelectionKey.OP_READ); } } } } // Close the socket mSocketChannel.close(); // If interrupted, throw an error if (mStop) { throw new IOException("transfer was cancelled"); } // Indicate success synchronized (mTransferStatus) { mTransferStatus.setState(TransferStatus.State.Succeeded); notifyStatusChangedListeners(); } } catch (IOException e) { synchronized (mTransferStatus) { mTransferStatus.setState(TransferStatus.State.Failed); mTransferStatus.setError(e.getMessage()); notifyStatusChangedListeners(); } } }