1

当Telnet 客户端断开连接时,AsynchronousSocketChannel触发它CompletionHandler的函数。completed(Integer result, ByteBuffer attachment)

resultInteger 是一个完全随机数。

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

这是完整的代码:

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

1 回答 1

1

根据文档,结果不会是随机的,它将是成功读取的字节数(大概在套接字断开之前):

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

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

于 2013-08-18T11:34:41.133 回答