Telnet客户端断开连接时,AsynchronousSocketChannel会触发其CompletionHandlercompleted(Integer result, ByteBuffer attachment)函数。

result整数是一个完全随机的数字。

我无法在收到新消息和客户端中断之间有所区别。我怎么解决这个问题?
如何过滤此事件,以便在实际消息和垃圾随机执行之间有所作为?

这是完整的代码:

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");
    }
});

最佳答案

根据the documentation,结果将不是随机的,而是成功读取的字节数(大概是在套接字断开连接之前):


  传递给完成处理程序的结果是读取的字节数,如果由于通道已到达流而无法读取任何字节,则返回-1。


我认为一定是客户端向您发送了您不期望的数据,并且该值实际上是正确的。

10-08 00:46