Example usage for java.nio.channels SocketChannel write

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

Introduction

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

Prototype

public final long write(ByteBuffer[] srcs) throws IOException 

Source Link

Usage

From source file:MainClass.java

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

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));

    for (;;) { // This server runs forever
        SocketChannel client = server.accept();
        String response = new java.util.Date().toString() + "\r\n";
        client.write(encoder.encode(CharBuffer.wrap(response)));
        client.close();//www  . j  a  v  a  2 s  .co  m
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);//from www  .  j a va 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:MainClass.java

public static void main(String[] argv) throws Exception {
    int port = 1234; // default

    ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
    ServerSocketChannel ssc = ServerSocketChannel.open();

    ssc.socket().bind(new InetSocketAddress(port));
    ssc.configureBlocking(false);//  ww w .  ja  va2 s. com

    while (true) {
        System.out.println("Waiting for connections");

        SocketChannel sc = ssc.accept();

        if (sc == null) {
            Thread.sleep(2000);
        } else {
            System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());

            buffer.rewind();
            sc.write(buffer);
            sc.close();
        }
    }
}

From source file:SimpleDaytimeServer.java

public static void main(String args[]) throws java.io.IOException {
    // RFC867 specifies port 13 for this service. On Unix platforms,
    // you need to be running as root to use that port, so we allow
    // this service to use other ports for testing.
    int port = 13;
    if (args.length > 0)
        port = Integer.parseInt(args[0]);

    // Create a channel to listen for connections on.
    ServerSocketChannel server = ServerSocketChannel.open();

    // Bind the channel to a local port. Note that we do this by obtaining
    // the underlying java.net.ServerSocket and binding that socket.
    server.socket().bind(new InetSocketAddress(port));

    // Get an encoder for converting strings to bytes
    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

    for (;;) { // Loop forever, processing client connections
        // Wait for a client to connect
        SocketChannel client = server.accept();

        // Build response string, wrap, and encode to bytes
        String date = new java.util.Date().toString() + "\r\n";
        ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

        // Send the response to the client and disconnect.
        client.write(response);
        client.close();/*  ww w. j  a  v  a2s .c  om*/
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();/*  w w w . ja  v  a  2s  . com*/
        Iterator it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();

            if (selKey.isAcceptable()) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
                SocketChannel sc = ssChannel.accept();
                ByteBuffer buf = ByteBuffer.allocate(100);
                int numBytesRead = sc.read(buf);

                if (numBytesRead == -1) {
                    sc.close();
                } else {
                    // Read the bytes from the buffer
                }
                int numBytesWritten = sc.write(buf);
            }
        }
    }
}

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   w  ww.  j a v a  2s  .  c  o 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:DaytimeServer.java

public static void main(String args[]) {
    try { // Handle startup exceptions at the end of this block
        // Get an encoder for converting strings to bytes
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

        // Allow an alternative port for testing with non-root accounts
        int port = 13; // RFC867 specifies this port.
        if (args.length > 0)
            port = Integer.parseInt(args[0]);

        // The port we'll listen on
        SocketAddress localport = new InetSocketAddress(port);

        // Create and bind a tcp channel to listen for connections on.
        ServerSocketChannel tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localport);

        // Also create and bind a DatagramChannel to listen on.
        DatagramChannel udpserver = DatagramChannel.open();
        udpserver.socket().bind(localport);

        // Specify non-blocking mode for both channels, since our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        // Register the channels with the selector, and specify what
        // conditions (a connection ready to accept, a datagram ready
        // to read) we'd like the Selector to wake up for.
        // These methods return SelectionKey objects, which we don't
        // need to retain in this example.
        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        // This is an empty byte buffer to receive emtpy datagrams with.
        // If a datagram overflows the receive buffer size, the extra bytes
        // are automatically discarded, so we don't have to worry about
        // buffer overflow attacks here.
        ByteBuffer receiveBuffer = ByteBuffer.allocate(0);

        // Now loop forever, processing client connections
        for (;;) {
            try { // Handle per-connection problems below
                // Wait for a client to connect
                selector.select();/* w w  w . jav a2  s  .  co m*/

                // If we get here, a client has probably connected, so
                // put our response into a ByteBuffer.
                String date = new java.util.Date().toString() + "\r\n";
                ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

                // Get the SelectionKey objects for the channels that have
                // activity on them. These are the keys returned by the
                // register() methods above. They are returned in a
                // java.util.Set.
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    // Get a key from the set, and remove it from the set
                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    // Get the channel associated with the key
                    Channel c = (Channel) key.channel();

                    // Now test the key and the channel to find out
                    // whether something happend on the TCP or UDP channel
                    if (key.isAcceptable() && c == tcpserver) {
                        // A client has attempted to connect via TCP.
                        // Accept the connection now.
                        SocketChannel client = tcpserver.accept();
                        // If we accepted the connection successfully,
                        // the send our respone back to the client.
                        if (client != null) {
                            client.write(response); // send respone
                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {
                        // A UDP datagram is waiting. Receive it now,
                        // noting the address it was sent from.
                        SocketAddress clientAddress = udpserver.receive(receiveBuffer);
                        // If we got the datagram successfully, send
                        // the date and time in a response packet.
                        if (clientAddress != null)
                            udpserver.send(response, clientAddress);
                    }
                }
            } catch (java.io.IOException e) {
                // This is a (hopefully transient) problem with a single
                // connection: we log the error, but continue running.
                // We use our classname for the logger so that a sysadmin
                // can configure logging for this server independently
                // of other programs.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.WARNING, "IOException in DaytimeServer", e);
            } catch (Throwable t) {
                // If anything else goes wrong (out of memory, for example)
                // then log the problem and exit.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.SEVERE, "FATAL error in DaytimeServer", t);
                System.exit(1);
            }
        }
    } catch (Exception e) {
        // This is a startup error: there is no need to log it;
        // just print a message and exit
        System.err.println(e);
        System.exit(1);
    }
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*from  w  w  w  . j  av 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:GetWebPageDemo.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*w  w w .  jav a2  s .  c o m*/
    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:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);/*from  w  w  w  .jav  a2s. c  om*/

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}