Jon*_*nas 19 java asynchronous nio java-7
我想用Java 7和NIO 2编写一个异步服务器.
但是我应该如何使用AsynchronousServerSocketChannel?
例如,如果我开始:
final AsynchronousServerSocketChannel server =
AsynchronousServerSocketChannel.open().bind(
new InetSocketAddress(port));
Run Code Online (Sandbox Code Playgroud)
然后,当我这样做时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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Sou*_*man 13
你在正确的轨道上,从完成的回调中调用accept()以接受更多连接应该工作.
一个简单(但丑陋)的方法来阻止线程终止只是循环直到线程被中断.
// yes, sleep() is evil, but sometimes I don't care
while (true) {
Thread.sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
更清洁的方法是使用AsynchronousChannelGroup.例如:
AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors
.newSingleThreadExecutor());
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(
new InetSocketAddress(port));
// (insert server.accept() logic here)
// wait until group.shutdown()/shutdownNow(), or the thread is interrupted:
group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
您可以调整线程的处理方式,有关详细信息,请参阅AsynchronousChannelGroup API文档.
| 归档时间: |
|
| 查看次数: |
11001 次 |
| 最近记录: |