Example usage for java.nio.channels SocketChannel open

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

Introduction

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

Prototype

public static SocketChannel open(SocketAddress remote) throws IOException 

Source Link

Document

Opens a socket channel and connects it to a remote address.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    int port = 1919;

    SocketAddress address = new InetSocketAddress("127.0.0.1", port);
    SocketChannel client = SocketChannel.open(address);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    IntBuffer view = buffer.asIntBuffer();

    for (int expected = 0;; expected++) {
        client.read(buffer);//  w  w w. j  a  va  2s.  c  om
        int actual = view.get();
        buffer.clear();
        view.rewind();

        if (actual != expected) {
            System.err.println("Expected " + expected + "; was " + actual);
            break;
        }
        System.out.println(actual);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    int port = 19;

    SocketAddress address = new InetSocketAddress("127.0.0.1", port);
    SocketChannel client = SocketChannel.open(address);

    ByteBuffer buffer = ByteBuffer.allocate(74);
    WritableByteChannel out = Channels.newChannel(System.out);

    while (client.read(buffer) != -1) {
        buffer.flip();/*from w  w  w  .j  a v  a2s .  c  o m*/
        out.write(buffer);
        buffer.clear();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    URL u = new URL("http://www.java2s.com");
    String host = u.getHost();/*from ww w .j  av  a  2  s  .  co m*/
    int port = 80;
    String file = "/";

    SocketAddress remote = new InetSocketAddress(host, port);
    SocketChannel channel = SocketChannel.open(remote);
    FileOutputStream out = new FileOutputStream("yourfile.htm");
    FileChannel localFile = out.getChannel();

    String request = "GET " + file + " HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n" + "Accept: text/*\r\n"
            + "Connection: close\r\n" + "Host: " + host + "\r\n" + "\r\n";

    ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
    channel.write(header);

    ByteBuffer buffer = ByteBuffer.allocate(8192);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        localFile.write(buffer);
        buffer.clear();
    }

    localFile.close();
    channel.close();
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);/*from w w w  .  ja  v  a  2s  .c om*/

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:Main.java

public static SocketChannel connect(int port) throws IOException {
    SocketAddress sa = new InetSocketAddress("127.0.0.1", port);
    return SocketChannel.open(sa);
}

From source file:org.springframework.boot.devtools.tunnel.server.SocketTargetServerConnection.java

@Override
public ByteChannel open(int socketTimeout) throws IOException {
    SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
    logger.trace("Opening tunnel connection to target server on " + address);
    SocketChannel channel = SocketChannel.open(address);
    channel.socket().setSoTimeout(socketTimeout);
    return new TimeoutAwareChannel(channel);
}

From source file:org.apache.james.imap.tester.builder.ScriptBuilder.java

public static ScriptBuilder open(String host, int port) throws Exception {
    InetSocketAddress address = new InetSocketAddress(host, port);
    SocketChannel socket = SocketChannel.open(address);
    socket.configureBlocking(false);/*from w  w w. ja v a  2  s  .  c o  m*/
    Client client = new Client(socket, socket);
    return new ScriptBuilder(client);
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static SocketChannel openClientSocket(Selector selector, SocketAddress endPointAddress)
        throws NetSocketException {
    SocketChannel toReturn;/*from  www  .j av a 2 s  .  c o m*/

    try {
        toReturn = SocketChannel.open(endPointAddress);
        toReturn.configureBlocking(false);
        toReturn.register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
        logger.error("IOException occurred while opening client socket", e);
        toReturn = null;
    }

    return toReturn;
}

From source file:InterruptibleSocketTest.java

/**
 * Connects to the test server, using interruptible I/O
 *///  ww  w  . ja va2s. c  o m
public void connectInterruptibly() throws IOException {
    messages.append("Interruptible:\n");
    SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 8189));
    try {
        in = new Scanner(channel);
        while (!Thread.currentThread().isInterrupted()) {
            messages.append("Reading ");
            if (in.hasNextLine()) {
                String line = in.nextLine();
                messages.append(line);
                messages.append("\n");
            }
        }
    } finally {
        channel.close();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                messages.append("Channel closed\n");
                interruptibleButton.setEnabled(true);
                blockingButton.setEnabled(true);
            }
        });
    }
}

From source file:jp.queuelinker.system.net.SelectorThread.java

public int connectChannel(final SocketAddress remoteAddress, final SelectorCallBack callBack)
        throws IOException {
    SocketChannel socketChannel = SocketChannel.open(remoteAddress);
    socketChannel.configureBlocking(false);
    // socketChannel.socket().setTcpNoDelay(true);
    socketChannel.socket().setReuseAddress(true);
    return addSocketChannel(socketChannel, callBack);
}