我应该如何使用 AsynchronousServerSocketChannel 来接受连接?
2022-09-02 04:26:00
我想使用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();
}
}
}