Example usage for java.nio.channels SelectionKey isConnectable

List of usage examples for java.nio.channels SelectionKey isConnectable

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey isConnectable.

Prototype

public final boolean isConnectable() 

Source Link

Document

Tests whether this key's channel has either finished, or failed to finish, its socket-connection operation.

Usage

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//from ww  w  .j a  v  a2s  .co  m
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:Main.java

public static boolean processReadySet(Set readySet) throws Exception {
    Iterator iterator = readySet.iterator();
    while (iterator.hasNext()) {
        SelectionKey key = (SelectionKey) iterator.next();
        iterator.remove();//  ww  w .  ja v a2 s .c  o  m
        if (key.isConnectable()) {
            boolean connected = processConnect(key);
            if (!connected) {
                return true; // Exit
            }
        }
        if (key.isReadable()) {
            String msg = processRead(key);
            System.out.println("[Server]: " + msg);
        }
        if (key.isWritable()) {
            System.out.print("Please enter a message(Bye to quit):");
            String msg = userInputReader.readLine();

            if (msg.equalsIgnoreCase("bye")) {
                return true; // Exit
            }
            SocketChannel sChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            sChannel.write(buffer);
        }
    }
    return false; // Not done yet
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private SelectionKey selectFirstConnectedSocketChannel(Selector selector) throws IOException {
    log.trace("selectFirstConnectedSocketChannel()");

    while (!selector.keys().isEmpty()) {
        if (selector.select(connectTimeout) == 0) { // Block until something happens
            return null;
        }//from w  ww . j  a v  a 2  s .c o m

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            if (key.isValid() && key.isConnectable()) {
                SocketChannel channel = (SocketChannel) key.channel();
                try {
                    if (channel.finishConnect()) {
                        return key;
                    }
                } catch (Exception e) {
                    key.cancel();
                    closeQuietly(channel);

                    log.trace("Error connecting socket channel: {}", e);
                }
            }

            it.remove();
        }
    }

    return null;
}

From source file:idgs.client.TcpClient.java

private synchronized void select() throws IOException {
    if (timeout > 0) {
        if (selector.select(timeout) == 0) {
            throw new SocketTimeoutException();
        }//from w ww .  j  av  a  2 s.c o m
    } else {
        selector.select();
    }

    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
        SelectionKey key = it.next();
        // handle connect
        if (key.isConnectable()) {
            processConnect(key);
        }
        // handle read
        else if (key.isReadable()) {
            processRead(key);
        }
        // handle write
        else if (key.isWritable()) {
            processWrite(key);
        }
        it.remove();
    }
}

From source file:idgs.client.TcpClient.java

private void processConnect(SelectionKey key) throws IOException {
    if (!isConnected.get()) {
        if (key.isConnectable()) {
            channel = (SocketChannel) key.channel();
            if (channel.isConnectionPending()) {
                channel.finishConnect();
                channel.configureBlocking(false);
                isConnected.set(true);//  w  ww.jav  a2 s .  c  om
                log.debug("connected to server: " + host);
                handler.onConnected(channel);
            }
        }
    } else {
        log.debug("already connected...");
    }
}

From source file:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??//from w  ww  .  ja va  2 s  .c o m
        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 {
                ; // 0
            }
        }
    }

}

From source file:co.elastic.tealess.SSLChecker.java

private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) {
    final InetSocketAddress address = sslReport.getAddress();
    try {/*from  w w  w  .  ja v a  2  s . co m*/
        logger.trace("Connecting to {}", address);
        Selector selector = Selector.open();
        SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT);
        socket.connect(address);
        selector.select(timeout);
        if (!sk.isConnectable()) {
            sslReport.setFailed(new SocketTimeoutException());
            return;
        }
        if (socket.isConnectionPending()) {
            socket.finishConnect();
        }
    } catch (ConnectException e) {
        logger.debug("Connection failed to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    } catch (IOException e) {
        logger.error("Failed connecting to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    }

    logger.debug("Connection successful to {}", address);
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

protected void processKey(SelectionKey key) {
    SessionSpi session = (SessionSpi) key.attachment();

    if (key.isAcceptable())
        session.onEvent(Constants.EV_ACCEPTABLE, null);
    if (key.isConnectable())
        session.onEvent(Constants.EV_CONNECTABLE, null);
    if (key.isValid() && key.isReadable())
        session.onEvent(Constants.EV_READABLE, null);
    if (key.isValid() && key.isWritable())
        session.onEvent(Constants.EV_WRITABLE, null);
}

From source file:edu.tsinghua.lumaqq.qq.net.Porter.java

/**
 * ??IPort./*w  ww.  j  a  v  a 2 s .  co  m*/
 * ???//.
 * @see IPort#send(ByteBuffer)
 * @see IPort#receive(ByteBuffer)
 * @see IPort#maintain()
 */
@Override
public void run() {
    log.debug("Porter??");
    int n = 0;
    while (!shutdown) {
        // do select
        try {
            n = selector.select(3000);
            // ?shutdownselector
            if (shutdown) {
                selector.close();
                break;
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            dispatchErrorToAll(e);
        }

        // ?
        processDisposeQueue();

        // select0?
        if (n > 0) {
            for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) {
                // Key
                SelectionKey sk = i.next();
                i.remove();
                // ?
                if (!sk.isValid())
                    continue;

                // ?
                INIOHandler handler = (INIOHandler) sk.attachment();
                try {
                    if (sk.isConnectable())
                        handler.processConnect(sk);
                    else if (sk.isReadable())
                        handler.processRead(sk);
                } catch (IOException e) {
                    log.error(e.getMessage());
                    handler.processError(e);
                } catch (PacketParseException e) {
                    log.debug("?: " + e.getMessage());
                } catch (RuntimeException e) {
                    log.error(e.getMessage());
                }
            }

            n = 0;
        }

        checkNewConnection();
        notifySend();
    }

    selector = null;
    shutdown = false;
    log.debug("Porter?");
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/*from  w w w  .jav  a 2  s  .  c  o  m*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}