【发布时间】:2012-01-20 11:31:22
【问题描述】:
我想使用 Java 7 和 NIO 2 编写一个异步服务器。
但是我应该如何使用AsynchronousServerSocketChannel?
例如如果我开始:
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().bind(
new InetSocketAddress(port));
然后当我执行server.accept() 时,程序终止,因为该调用是异步。如果我将该代码放入无限循环中,则会抛出 AcceptPendingException。
关于如何使用AsynchronousServerSocketChannel 编写简单的异步服务器有什么建议吗?
这是我的完整示例(类似于 JavaDoc 中的示例):
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AsyncServer {
public static void main(String[] args) {
int port = 8060;
try {
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().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");
// accept the next connection
server.accept("Client connection", this);
// handle this connection
//TODO handle(ch);
}
public void failed(Throwable exc, Object att) {
System.out.println("Failed to accept connection");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
您可以使用专门用于客户端-服务器应用程序的 Netty 框架。它还使用 java NIO。服务器开发简单快捷。通过netty.io
-
@Optimus:我知道netty,但这与这个问题无关。
标签: java asynchronous nio java-7