AsynchronousSocketChannel

AsynchronousSocketChannel

我正在尝试使用CompletionHandler而不是Futures在vert.x辅助版本中的AsynchronousSocketChannel上实现单个请求/响应。从vert.x文档中:

“工作台永远不会由多个线程同时执行。”

所以这是我的代码(不确定我是否正确处理了套接字的100%-请发表评论):

    // ommitted: asynchronousSocketChannel.open, connect ...

    eventBus.registerHandler(address, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(final Message<JsonObject> event) {
            final ByteBuffer receivingBuffer = ByteBuffer.allocateDirect(2048);
            final ByteBuffer sendingBuffer = ByteBuffer.wrap("Foo".getBytes());

            asynchronousSocketChannel.write(sendingBuffer, 0L, new CompletionHandler<Integer, Long>() {
                public void completed(final Integer result, final Long attachment) {
                    if (sendingBuffer.hasRemaining()) {
                        long newFilePosition = attachment + result;
                        asynchronousSocketChannel.write(sendingBuffer, newFilePosition, this);
                    }

                    asynchronousSocketChannel.read(receivingBuffer, 0L, new CompletionHandler<Integer, Long>() {
                        CharBuffer charBuffer = null;
                        final Charset charset = Charset.defaultCharset();
                        final CharsetDecoder decoder = charset.newDecoder();

                        public void completed(final Integer result, final Long attachment) {
                            if (result > 0) {
                                long p = attachment + result;
                                asynchronousSocketChannel.read(receivingBuffer, p, this);
                            }

                            receivingBuffer.flip();

                            try {
                                charBuffer = decoder.decode(receivingBuffer);
                                event.reply(charBuffer.toString()); // pseudo code
                            } catch (CharacterCodingException e) { }


                        }

                        public void failed(final Throwable exc, final Long attachment) { }
                    });
                }

                public void failed(final Throwable exc, final Long attachment) { }
            });
        }
    });

在负载测试期间,我遇到了很多ReadPendingException和WritePendingException的问题,如果handle方法中实际上一次只有一个线程,这似乎有些奇怪。如果一次只有1个线程与AsynchronousSocketChannel一起工作,怎么可能没有完全完成读取或写入操作?

最佳答案

来自AsynchronousSocketChannel的处理程序在其自己的AsynchronousChannelGroup上执行,该组是ExecutorService的派生类。除非您做出特殊的努力,否则处理程序将与启动I / O操作的代码并行执行。

要在一个Verticle中执行I / O完成处理程序,您必须在该Verticle中创建并注册一个处理程序,该处理程序现在执行AsynchronousSocketChannel的处理程序。

AsynchronousSocketChannel的处理程序应仅将其参数(结果和附件)打包在消息中,然后将该消息发送到事件总线。

07-24 18:31