Example usage for java.nio.channels SocketChannel finishConnect

List of usage examples for java.nio.channels SocketChannel finishConnect

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel finishConnect.

Prototype

public abstract boolean finishConnect() throws IOException;

Source Link

Document

Finishes the process of connecting a socket channel.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);/*w  w  w . ja v  a2s . c om*/

    sChannel.connect(new InetSocketAddress("hostName", 12345));

    while (!sChannel.finishConnect()) {
        // Do something else
    }

}

From source file:MainClass.java

public static void main(String[] argv) throws Exception {
    String host = "localhost";
    int port = 80;

    InetSocketAddress addr = new InetSocketAddress(host, port);
    SocketChannel sc = SocketChannel.open();

    sc.configureBlocking(false);/*from  w w  w.java  2 s  .  c  o m*/

    System.out.println("initiating connection");

    sc.connect(addr);

    while (!sc.finishConnect()) {
        System.out.println("doing something useless");
    }

    System.out.println("connection established");

    sc.close();
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*from  ww  w.jav a2 s. c o  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 processConnect(SelectionKey key) throws Exception {
    SocketChannel channel = (SocketChannel) key.channel();
    while (channel.isConnectionPending()) {
        channel.finishConnect();
    }//  w  w  w .j a  v  a  2  s .  c om
    return true;
}

From source file:com.buaa.cfs.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 *
 * @param channel  - this should be a {@link SelectableChannel}
 * @param endpoint//w  w w . j a  va2 s.co  m
 *
 * @throws IOException
 * @see SocketChannel#connect(SocketAddress)
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (Time.now() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 * /*ww  w  . j a  v  a  2 s  . co  m*/
 * @see SocketChannel#connect(SocketAddress)
 * @param channel
 *        - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

From source file:com.byteatebit.nbecho.perfclient.NbEchoPerfClient.java

@Override
public void accept(INbContext nbContext, SocketChannel socketChannel) {
    boolean connectionFinished = false;
    int taskId = createTaskId();
    try {/*ww w.  ja va  2  s. c o  m*/
        connectionFinished = socketChannel.finishConnect();
    } catch (IOException e) {
        LOG.error("Could not complete socket connection.", e);
    }
    if (!connectionFinished) {
        LOG.error("Could not complete socket connection.  Closing socket channel");
        IOUtils.closeQuietly(socketChannel);
        countDownLatch.countDown();
        return;
    }
    WriteMessageTask writeMessageTask = WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(1024)).build();
    ReadDelimitedMessageTask readMessageTask = ReadDelimitedMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(1024)).withDelimiter(MESSAGE_DELIMITER).build();
    clientTask(nbContext, socketChannel, readMessageTask, writeMessageTask, numRequests, taskId);
}

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;
        }/*w w w.  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:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??/* w  w w  . ja v a2  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:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

private void doConnect(SelectionKey key) {

    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final SocketChannel socketChannel = (SocketChannel) key.channel();
    try {/*from   ww w .  j  a  v  a  2 s .  c  o m*/
        while (!socketChannel.finishConnect()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                LOG.error(e1);
            }
        }

        final SelectionKey channelKey = socketChannel.register(selector,
                SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        outgoingConnection.setSelectionKey(channelKey);
        channelKey.attach(outgoingConnection);

    } catch (IOException ioe) {
        outgoingConnection.reportConnectionProblem(ioe);
    }
}