Example usage for java.nio.channels AsynchronousSocketChannel write

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

Introduction

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

Prototype

@Override
public final <A> void write(ByteBuffer src, A attachment, CompletionHandler<Integer, ? super A> handler)

    

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    SocketAddress serverAddr = new InetSocketAddress("localhost", 8989);
    Future<Void> result = channel.connect(serverAddr);
    result.get();//from  w w w  .  ja  v a2s .c om
    System.out.println("Connected");
    Attachment attach = new Attachment();
    attach.channel = channel;
    attach.buffer = ByteBuffer.allocate(2048);
    attach.isRead = false;
    attach.mainThread = Thread.currentThread();

    Charset cs = Charset.forName("UTF-8");
    String msg = "Hello";
    byte[] data = msg.getBytes(cs);
    attach.buffer.put(data);
    attach.buffer.flip();

    ReadWriteHandler readWriteHandler = new ReadWriteHandler();
    channel.write(attach.buffer, attach, readWriteHandler);
    attach.mainThread.join();
}