AsynchronousSocketChannel中的CompletionHandler(AsynchronousSocketChannel,Object)

时间:2016-02-26 09:13:27

标签: java

我使用Java异步IO编写聊天室服务器,这里是代码:

class AcceptHandler
        implements CompletionHandler<AsynchronousSocketChannel, Object> {

    private AsynchronousServerSocketChannel serverChannel;

    public AcceptHandler(AsynchronousServerSocketChannel sc) {
        this.serverChannel = sc;
    }

    ByteBuffer buff = ByteBuffer.allocate(1024);

    @Override
    public void completed(AsynchronousSocketChannel sc, Object attachment) {
        AIOServer.channelList.add(sc);

        serverChannel.accept(null, this);
        sc.read(buff, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("there is a message");
                buff.flip();
                String content = StandardCharsets.UTF_8.decode(buff).toString();
                for (AsynchronousSocketChannel c : AIOServer.channelList) {
                    try {
                        c.write(ByteBuffer.wrap(content.getBytes(AIOServer.UTF_8))).get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                buff.clear();
                sc.read(buff, null, this);
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.out.println("error: " + exc);

                AIOServer.channelList.remove(sc);
            }
        });
    }

    @Override
    public void failed(Throwable exc, Object attachment) {
        System.out.println("connect failed: " + exc);
    }
}

客户端连接并且此功能将回调,几个客户端可以互相聊天。但是当客户端关闭时,客户端断开连接,&#34;有一条消息&#34;将继续打印,如下所示: enter image description here

有人可以给我一个答案吗?

0 个答案:

没有答案