Search code examples
javaasyncsocket

java.lang.NullPointerException at sun.nio.ch.AsynchronousSocketChannelImpl.read


this is my code and i have below problem for reading ...when connection accepted it will happen!

    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();
        }
    }

log and error:

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)

what is my problem and when it solved does arg0 fill with what it reads?
any help aperciated.


Solution

  • Given

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

    Don't you need to allocate your ByteBuffer first ?

    e.g.

       ByteBuffer buffer = ByteBuffer.allocate(size);