Respect,
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:
I create handlers for writing and reading data:
ReadHandler:
public class ReadHandler implements CompletionHandler<Integer, Msg> {
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());
}
}
ClientWriteHandler
public class ClientWriteHandler implements CompletionHandler<Integer, Msg> {
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);
}
}
Then I call write method 2 time
socket = AsynchronousSocketChannel.open();
socket.connect(new InetSocketAddress("localhost", port)).get();
writeHandler = new ClientWriteHandler(this);
writeHandler.write("hellooo server :)");
writeHandler.write("hellooo server again :)");
I try to use clear() function on the ByteBuffer but no effect. Any suggestion?