Writing an Asynchronous Client Based on Future - Java Network

Java examples for Network:Socket Channel

Description

Writing an Asynchronous Client Based on Future

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.concurrent.ExecutionException;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());
    CharBuffer charBuffer;/*from  w  w w.j  a v  a 2 s. com*/
    Charset charset = Charset.defaultCharset();
    CharsetDecoder decoder = charset.newDecoder();
    try (AsynchronousSocketChannel asyncChannel = AsynchronousSocketChannel
        .open()) {
      if (asyncChannel.isOpen()) {
        asyncChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
        asyncChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        asyncChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
        Void connect = asyncChannel.connect(
            new InetSocketAddress("127.0.0.1", 5555)).get();
        if (connect == null) {
          System.out
              .println("Local address: " + asyncChannel.getLocalAddress());
          asyncChannel.write(helloBuffer).get();
          while (asyncChannel.read(buffer).get() != -1) {
            buffer.flip();
            charBuffer = decoder.decode(buffer);
            System.out.println(charBuffer.toString());
            if (buffer.hasRemaining()) {
              buffer.compact();
            } else {
              buffer.clear();
            }
            asyncChannel.write(ByteBuffer.wrap("test".getBytes())).get();
          }
        } else {
          System.out.println("The connection cannot be established!");
        }
      } else {
        System.out.println("The asynchronous socket channel cannot be opened!");
      }
    } catch (IOException | InterruptedException | ExecutionException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials