Question

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.

Was it helpful?

Solution

Given

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

Don't you need to allocate your ByteBuffer first ?

e.g.

   ByteBuffer buffer = ByteBuffer.allocate(size);

OTHER TIPS

I guess that the line ch.read(arg0); causes the error. You set arg0 to null and then try to write into it, but before that you probably need to initialize it like so:arg0=ByteBuffer.allocate(desired_capacity);

If you do not know which capacity to choose, you could set the ByteBuffer to the maximum size that is to be expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top