Java Code Examples for java.nio.channels.SelectionKey#OP_CONNECT

The following examples show how to use java.nio.channels.SelectionKey#OP_CONNECT . 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: SocketIOWithTimeout.java    From big-c with Apache License 2.0 6 votes vote down vote up
private static String timeoutExceptionString(SelectableChannel channel,
                                             long timeout, int ops) {
  
  String waitingFor;
  switch(ops) {
  
  case SelectionKey.OP_READ :
    waitingFor = "read"; break;
    
  case SelectionKey.OP_WRITE :
    waitingFor = "write"; break;      
    
  case SelectionKey.OP_CONNECT :
    waitingFor = "connect"; break;
    
  default :
    waitingFor = "" + ops;  
  }
  
  return timeout + " millis timeout while " +
         "waiting for channel to be ready for " + 
         waitingFor + ". ch : " + channel;    
}
 
Example 2
Source File: SelectorImpl.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void update(Selectable selectable) {
    if (selectable.getChannel() != null) {
        int interestedOps = 0;
        if (selectable.getChannel() instanceof SocketChannel &&
                ((SocketChannel)selectable.getChannel()).isConnectionPending()) {
            interestedOps |= SelectionKey.OP_CONNECT;
        } else {
            if (selectable.isReading()) {
                if (selectable.getChannel() instanceof ServerSocketChannel) {
                    interestedOps |= SelectionKey.OP_ACCEPT;
                } else {
                    interestedOps |= SelectionKey.OP_READ;
                }
            }
            if (selectable.isWriting()) interestedOps |= SelectionKey.OP_WRITE;
        }
        SelectionKey key = selectable.getChannel().keyFor(selector);
        key.interestOps(interestedOps);
    }
}
 
Example 3
Source File: SocketIOWithTimeout.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static String timeoutExceptionString(SelectableChannel channel,
                                             long timeout, int ops) {
  
  String waitingFor;
  switch(ops) {
  
  case SelectionKey.OP_READ :
    waitingFor = "read"; break;
    
  case SelectionKey.OP_WRITE :
    waitingFor = "write"; break;      
    
  case SelectionKey.OP_CONNECT :
    waitingFor = "connect"; break;
    
  default :
    waitingFor = "" + ops;  
  }
  
  return timeout + " millis timeout while " +
         "waiting for channel to be ready for " + 
         waitingFor + ". ch : " + channel;    
}
 
Example 4
Source File: SelectionKeyTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.nio.channels.SelectionKey#isConnectable()
 */
public void test_isConnectable() {
    MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_CONNECT);
    assertTrue(mockSelectionKey1.isConnectable());
    MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
    assertFalse(mockSelectionKey2.isConnectable());
}
 
Example 5
Source File: TCPConnection.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
public TCPConnection(ConnectionId id, Client client, Selector selector, IPv4Header ipv4Header, TCPHeader tcpHeader) throws IOException {
    super(id, client);

    TCPHeader shrinkedTcpHeader = tcpHeader.copy();
    shrinkedTcpHeader.shrinkOptions(); // no TCP options

    networkToClient = new Packetizer(ipv4Header, shrinkedTcpHeader);
    networkToClient.getResponseIPv4Header().swapSourceAndDestination();
    networkToClient.getResponseTransportHeader().swapSourceAndDestination();

    SelectionHandler selectionHandler = (selectionKey) -> {
        if (selectionKey.isValid() && selectionKey.isConnectable()) {
            processConnect();
        }
        if (selectionKey.isValid() && selectionKey.isReadable()) {
            processReceive();
        }
        if (selectionKey.isValid() && selectionKey.isWritable()) {
            processSend();
        }
        updateInterests();
    };
    channel = createChannel();
    // interests will be set on the first packet received
    // set the initial value now so that they won't need to be updated
    interests = SelectionKey.OP_CONNECT;
    selectionKey = channel.register(selector, interests, selectionHandler);
}
 
Example 6
Source File: PassiveRedisIndexer.java    From bt with Apache License 2.0 5 votes vote down vote up
@Override
public int calcInterestOps() {
	int ops = SelectionKey.OP_READ;
	
	if(chan.isConnectionPending())
		ops |= SelectionKey.OP_CONNECT;
	
	if(awaitingWriteNotification)
		ops |= SelectionKey.OP_WRITE;
		
	return ops;
}
 
Example 7
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
String printSelectionOps(SelectionKey key) {
    StringBuffer sb=new StringBuffer();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) !=0)
        sb.append("OP_ACCEPT ");
    if ((key.readyOps() & SelectionKey.OP_CONNECT) !=0)
        sb.append("OP_CONNECT ");
    if ((key.readyOps() & SelectionKey.OP_READ) !=0)
        sb.append("OP_READ ");
    if ((key.readyOps() & SelectionKey.OP_WRITE) !=0)
        sb.append("OP_WRITE ");
    return sb.toString();
}
 
Example 8
Source File: SctpChannelImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & PollArrayWrapper.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (PollArrayWrapper.POLLERR
                | PollArrayWrapper.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & PollArrayWrapper.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & PollArrayWrapper.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & PollArrayWrapper.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 9
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 10
Source File: PlainHttpConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public int interestOps() {
    return SelectionKey.OP_CONNECT;
}
 
Example 11
Source File: SctpChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 12
Source File: LotsOfCancels.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 13
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 14
Source File: SctpChannelImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 15
Source File: SctpChannelImpl.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & PollArrayWrapper.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (PollArrayWrapper.POLLERR
                | PollArrayWrapper.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & PollArrayWrapper.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & PollArrayWrapper.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & PollArrayWrapper.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 16
Source File: SctpChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 17
Source File: SctpChannel.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}
 
Example 18
Source File: SctpChannel.java    From jdk8u-jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}
 
Example 19
Source File: SctpChannel.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}
 
Example 20
Source File: SelectionRegistration.java    From DeviceConnect-Android with MIT License 2 votes vote down vote up
/**
 * Indicates if the NIO channel is connectable.
 * 
 * @return True if the NIO channel is connectable.
 */
public boolean isConnectable() {
    return (getReadyOperations() & SelectionKey.OP_CONNECT) != 0;
}