0

这是我的代码,我有以下阅读问题......当连接被接受时,它会发生!

    int port = 8080;
        try {
            final AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors
                    .newSingleThreadExecutor());
            final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(
                    new InetSocketAddress(port));

            System.out.println("Server listening on " + port);
            server.accept("Client connection", 
                    new CompletionHandler<AsynchronousSocketChannel, Object>() {
                public void completed(AsynchronousSocketChannel ch, Object att) {
                    System.out.println("Accepted a connection");
                    ByteBuffer arg0= null;
                    ch.read(arg0);
                    System.out.println(arg0.toString());
                    server.accept("Client connection", this);
                }

                public void failed(Throwable exc, Object att) {
                    System.out.println("Failed to accept connection");
                }
            });
            group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

日志和错误:

Server listening on 8080
Accepted a connection
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
    at sun.nio.ch.AsynchronousSocketChannelImpl.read(AsynchronousSocketChannelImpl.java:277)
    at SafeSurf$1.completed(SafeSurf.java:27)
    at SafeSurf$1.completed(SafeSurf.java:1)
    at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126)
    at sun.nio.ch.Invoker$2.run(Invoker.java:206)
    at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

我的问题是什么,当它解决时,arg0 是否填充了它所读取的内容?
有任何帮助。

4

2 回答 2

1

给定

   ByteBuffer arg0= null;
   ch.read(arg0);

你不需要分配你的ByteBuffer第一个吗?

例如

   ByteBuffer buffer = ByteBuffer.allocate(size);
于 2013-08-21T14:01:48.213 回答
0

我猜该行ch.read(arg0);会导致错误。您将 arg0 设置为 null 然后尝试写入它,但在此之前您可能需要像这样初始化它:arg0=ByteBuffer.allocate(desired_capacity);

如果您不知道选择哪种容量,可以将 ByteBuffer 设置为预期的最大大小。

于 2013-08-21T14:07:04.020 回答