简体   繁体   English

AsynchronousSocketChannel #read永远不会完成。

[英]AsynchronousSocketChannel#read is never completing.

I'm experimenting with NIO2 and running into an issue. 我正在尝试使用NIO2并遇到问题。

Here's the code I'm using: 这是我正在使用的代码:

ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
    channel.read(buffer, null, new CompletionHandler<Integer, Object>() {
        @Override
        public void completed(Integer result, Object attachment) {
            Packet packet = new Packet(buffer.getInt(), buffer);
            PacketHandler handler = PacketHandler.forOpcode(packet.getOpcode());
            if(!Objects.isNull(handler)) {
                handler.handle(channel, packet);
            } else {
                System.out.println("Unexpected opcode received from client. Opcode: " + packet.getOpcode());
            }
        }

        @Override
        public void failed(Throwable exc, Object attachment) {
            System.out.println("DEBUG A");
            exc.printStackTrace();
        }
    });

The issue is that no-matter what I send the server, it never completes. 问题是无论我发送什么服务器,它永远不会完成。 For testing purposes I have a very flat-format login packet set up and I'm sending this data through the client: 出于测试目的,我设置了一个非常平面格式的登录数据包,我将通过客户端发送此数据:

    ByteBuffer buffer = ByteBuffer.allocate(28);
    buffer.putInt(1); //opcode
    ByteBufferUtils.putString(buffer, "admin");
    ByteBufferUtils.putString(buffer, "admin");
    channel.write(buffer);

Even though the client writes the data, the server never finishes reading this. 即使客户端写入数据,服务器也永远不会完成读取。 I've also made sure that (DEFAULT_BUFFER_SIZE) was equal to the sent buffer size to see if that was the issue, but there were still not any changes in functionality. 我还确保(DEFAULT_BUFFER_SIZE)等于发送的缓冲区大小以查看是否存在问题,但功能上仍然没有任何变化。

Whenever I disconnect the client (Currently using a thread to keep it alive, for absolutely no reason) I get the following print stack trace from #failed 每当我断开客户端时(当前使用线程使其保持活动状态,绝对没有理由)我从#failed获得以下打印堆栈跟踪

java.io.IOException: The specified network name is no longer available.
at sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:309)
at sun.nio.ch.Iocp.access$700(Iocp.java:46)
at sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:399)
at java.lang.Thread.run(Thread.java:745)

You aren't sending anything. 你没有发送任何东西。 You need to flip() the buffer before calling write(), and compact() it afterwards. 你需要在调用write(),之前flip()缓冲区write(),然后compact()它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM