Example usage for java.nio.channels SocketChannel connect

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

Introduction

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

Prototype

public abstract boolean connect(SocketAddress remote) throws IOException;

Source Link

Document

Connects this channel's socket.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);/*from w w  w.  j  a  v  a2  s  .c  o  m*/

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

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

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);//  w  ww. j a v  a  2s  .  c  om
    sChannel.connect(new InetSocketAddress("hostName", 12345));

    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    buf.put((byte) 0xFF);

    buf.flip();

    int numBytesWritten = sChannel.write(buf);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);/*  w  w w . ja  v a  2 s  . c o m*/
    sChannel.connect(new InetSocketAddress("hostName", 12345));

    int numBytesRead = sChannel.read(buf);

    if (numBytesRead == -1) {
        sChannel.close();
    } else {
        buf.flip();
    }
}

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);/*  w  w  w. j a  v a  2s  . 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:Main.java

public static void main(String[] args) throws Exception {
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    int port = 19000;
    InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port);
    Selector selector = Selector.open();
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);//from  w  w w .  ja va 2 s .com
    channel.connect(serverAddress);
    int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    channel.register(selector, operations);

    userInputReader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        if (selector.select() > 0) {
            boolean doneStatus = processReadySet(selector.selectedKeys());
            if (doneStatus) {
                break;
            }
        }
    }
    channel.close();
}

From source file:GetWebPageDemo.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//from  w  ww .  j av a2 s .  com
    int slashPos;

    resource = "www.java2s.com/index.htm";
    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.connect(socketAddress);

        String request = "GET " + file + " \r\n\r\n";
        channel.write(encoder.encode(CharBuffer.wrap(request)));

        while ((channel.read(buffer)) != -1) {
            buffer.flip();
            decoder.decode(buffer, charBuffer, false);
            charBuffer.flip();
            System.out.println(charBuffer);
            buffer.clear();
            charBuffer.clear();
        }
    } 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:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*from  ww  w .j av  a 2 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: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  av a2 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 av  a2  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:gridool.util.net.PoolableSocketChannelFactory.java

private static SocketChannel createSocketChannel(final SocketAddress sockAddr, final boolean blocking,
        final int rcvbufSize) {
    final SocketChannel ch;
    try {// w  ww .j ava 2 s .  co m
        ch = SocketChannel.open();
        ch.configureBlocking(blocking);
    } catch (IOException e) {
        LOG.error("Failed to open SocketChannel.", e);
        throw new IllegalStateException(e);
    }
    final Socket sock = ch.socket();
    if (rcvbufSize != -1) {
        try {
            sock.setReceiveBufferSize(rcvbufSize);
        } catch (SocketException e) {
            LOG.error("Failed to setReceiveBufferSize.", e);
            throw new IllegalStateException(e);
        }
    }
    try {
        ch.connect(sockAddr);
    } catch (IOException e) {
        LOG.error("Failed to connect socket: " + sockAddr, e);
        throw new IllegalStateException(e);
    }
    return ch;
}