Writing Socket Client SocketChannel - Java Network

Java examples for Network:Socket Channel

Description

Writing Socket Client SocketChannel

Demo Code

import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocateDirect(2 * 1024);
    Charset charset = Charset.defaultCharset();
    CharsetDecoder decoder = charset.newDecoder();
    try (Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open()) {
      if ((socketChannel.isOpen()) && (selector.isOpen())) {
        socketChannel.configureBlocking(false);
        socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
        socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new java.net.InetSocketAddress("127.0.0.1", 4444));
        System.out.println("Localhost: " + socketChannel.getLocalAddress());
        while (selector.select(1000) > 0) {
          Set keys = selector.selectedKeys();
          Iterator its = keys.iterator();
          while (its.hasNext()) {
            SelectionKey key = (SelectionKey) its.next();
            its.remove();// w  w  w . j  a  va 2s . co  m
            try (SocketChannel keySocketChannel = (SocketChannel) key.channel()) {
              if (key.isConnectable()) {
                System.out.println("I am connected!");
                if (keySocketChannel.isConnectionPending()) {
                  keySocketChannel.finishConnect();
                }
                while (keySocketChannel.read(buffer) != -1) {
                  buffer.flip();
                  CharBuffer charBuffer = decoder.decode(buffer);
                  System.out.println(charBuffer.toString());
                  if (buffer.hasRemaining()) {
                    buffer.compact();
                  } else {
                    buffer.clear();
                  }
                  keySocketChannel.write(ByteBuffer.wrap("Random number:".getBytes("UTF-8")));
                }
              }
            } catch (IOException ex) {
              System.err.println(ex);
            }
          }
        }
      } else {
        System.out.println("The socket channel or selector cannot be opened!");
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Related Tutorials