尊重閱讀所有郵件,AsynchronousSocketChannel寫/在一個
我嘗試使用新的Java NIO2到客戶端和服務器端建立異步的SocketChannel和溝通,但問題是,我發送的所有郵件到插座上服務器,套接字全部讀取爲一條消息。這裏是代碼:
創建寫入處理和讀取數據:
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);
}
}
然後我調用write方法2時
socket = AsynchronousSocketChannel.open();
socket.connect(new InetSocketAddress("localhost", port)).get();
writeHandler = new ClientWriteHandler(this);
writeHandler.write("hellooo server :)");
writeHandler.write("hellooo server again :)");
我嘗試在字節緩衝區,但沒有效果明確的使用()函數。任何建議?
Oke但如果我的ByteBuffer已滿,我該怎麼辦,我嘗試清除bytebuffer,但後來收到錯誤消息 線程「main」中的異常java.nio.channels.WritePendingException – user2803095