当Telnet 客户端断开连接时,AsynchronousSocketChannel
触发它CompletionHandler
的函数。completed(Integer result, ByteBuffer attachment)
result
Integer 是一个完全随机数。
我无法区分接收新消息和客户端断开连接。我怎么解决这个问题?如何过滤此事件,以便在实际消息和垃圾随机执行之间有所不同?
这是完整的代码:
final AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(4242));
System.out.println("Starting server...");
serverSocket.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel clientSocket, Void attachment) {
System.out.println("Client connected");
final int clientndex = clients.size();
clients.put(clientndex, "Something...");
final ByteBuffer clientBuffer = ByteBuffer.allocateDirect(256);
clientSocket.read(clientBuffer, null, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) { //### This fires randomly
clientBuffer.flip();
try {
System.out.println("LEN" + result + " message received from " + clientndex + ": " + bufferDecoder.decode(clientBuffer).toString());
} catch (CharacterCodingException ex) {
System.out.println("Bad encoding");
}
clientBuffer.clear();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("Read error");
}
});
serverSocket.accept(null, this);
}
@Override
public void failed(Throwable exc, Void attachment) {
System.out.println("Conn error");
}
});