title: AsynchronousSocketChannel write/read all messages in one
body: <p>Respect,</p>
  
  <p>I try to use new Java NIO2 to create Asynchronous SocketChannel on the client and on the server side and communicate, but problem is that all messages I sent to socket on the server, socket read all as one message. here is code:</p>
  
  <p>I  create handlers for writing and reading data:</p>
  
  <p>ReadHandler:</p>
  
  <pre><code>public class ReadHandler implements CompletionHandler&lt;Integer, Msg&gt; {
  
  
  private AsynchronousSocketChannel _socket;
  private SocketHandler _socketHandler;
  
  private ByteBuffer _buffer;
  
  public ReadHandler(SocketHandler socketHandler) {
  
      this._socketHandler = socketHandler;
      _buffer = ByteBuffer.allocate(100);
  
      this._socket = this._socketHandler.getSocket();
      this._socket.read(_buffer, null, this);
  }
  
  @Override
  public void completed(Integer result, Msg attachment) {
  
      System.out.println("readdddd " + result);
  
      String message = new String(_buffer.array());
      System.out.println("mess:" + message);
  
  }
  
  @Override
  public void failed(Throwable exc, Msg attachment) {
      System.out.println(exc.getMessage());
  }
  </code></pre>
  
  <p>}</p>
  
  <p>ClientWriteHandler</p>
  
  <pre><code>public class ClientWriteHandler implements CompletionHandler&lt;Integer, Msg&gt; {
  
  private AsynchronousSocketChannel _socket;
  private ClientSocket _clientHandler;
  
  private ByteBuffer _buffer;
  
  public ClientWriteHandler(ClientSocket clientHandler) {
  
  
      this._clientHandler = clientHandler;
      _buffer = ByteBuffer.allocate(2048);
      this._socket = this._clientHandler.getSocket();
  }
  
  @Override
  public void completed(Integer result, Msg attachment) {
  
      System.out.println("write " + result);
      _buffer.clear();
  }
  
  @Override
  public void failed(Throwable exc, Msg attachment) {
      System.out.println(exc.getMessage());
  }
  
  public void write(String data) {
      _buffer = ByteBuffer.allocate(2048);
      this._socket.write(_buffer.wrap(data.getBytes()), new Msg(), this);
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Then I call write method 2 time</p>
  
  <pre><code>socket = AsynchronousSocketChannel.open();
          socket.connect(new InetSocketAddress("localhost", port)).get();
          writeHandler = new ClientWriteHandler(this);
          writeHandler.write("hellooo server :)");
          writeHandler.write("hellooo server again :)");
  </code></pre>
  
  <p>I try to use clear() function on the ByteBuffer but no effect. Any suggestion?</p>