Code example for SocketChannel

Methods: connect, finishConnect, isConnected, register

0
    @Override 
    public boolean connect(SocketAddress remote) throws IOException {
 
        long start = System.currentTimeMillis();
        //log.debug("trying to connect"); 
        socketChannel.connect(remote);
        while (selector.select(connectTimeout) > 0) {
            selector.selectedKeys().remove(channelKey);
            //log.debug("selected connect"); 
            //log.debug("Spent " + (System.currentTimeMillis() - start)); 
            if (!channelKey.isConnectable()) {
                throw new IllegalStateException("Socket channel is in not connectable state");
            } 
 
            socketChannel.finishConnect();
            channelKey = socketChannel.register(selector, SelectionKey.OP_READ);
            if (log.isDebugEnabled()) {
                log.debug("Connected socket in " + (System.currentTimeMillis() - start));
            } 
            if (!socketChannel.isConnected()) {
                throw new SocketException("SocketChannel not connected on some reason");
            } 
            return true; 
        } 
        //log.debug("Spent " + (System.currentTimeMillis() - start));