这是我的代码,我有下面的问题,阅读...when连接,接受它会发生!
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是否充满了它所读到的内容?
任何帮助都可以。
发布于 2013-08-21 14:01:48
给定的
ByteBuffer arg0= null;
ch.read(arg0);你不需要先分配你的ByteBuffer吗?
例如:
ByteBuffer buffer = ByteBuffer.allocate(size);发布于 2013-08-21 14:07:04
我猜ch.read(arg0);行会导致错误。您将arg0设置为null,然后尝试写入它,但在此之前,您可能需要像这样初始化它:arg0=ByteBuffer.allocate(desired_capacity);
如果不知道要选择哪种容量,则可以将ByteBuffer设置为预期的最大大小。
https://stackoverflow.com/questions/18359501
复制相似问题