[英]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? 我的问题是什么,当它解决后,arg0会填充读取的内容吗?
any help aperciated. 任何帮助。
Given 给定
ByteBuffer arg0= null;
ch.read(arg0);
Don't you need to allocate your ByteBuffer
first ? 您是否不需要首先分配
ByteBuffer
?
eg 例如
ByteBuffer buffer = ByteBuffer.allocate(size);
I guess that the line ch.read(arg0);
我猜这行
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);
您将arg0设置为null,然后尝试对其进行写入,但是在此之前,您可能需要像这样将其初始化:
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. 如果您不知道选择哪个容量,可以将ByteBuffer设置为期望的最大大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.