我有一个小型服务器设置,我正在尝试使用基于事件的连接套接字,以便在每个传入连接上调用处理程序。它适用于第一个连接,但在第一个连接之后不接受任何新连接。
为简单起见,我只是关闭客户端连接。另外,是的,第一次连接后服务器仍在运行,它不会终止。
这是代码:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ServerTest
{
static CompletionHandler<AsynchronousSocketChannel, Object> handler =
new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
System.out.println(attachment + " completed with " + result + " bytes written");
try {
result.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable e, Object attachment) {
System.err.println(attachment + " failed with:");
e.printStackTrace();
}
};
public static void main(String[] args) throws Exception
{
AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newSingleThreadExecutor());
System.out.println("STARTING");
AsynchronousServerSocketChannel ssc =
AsynchronousServerSocketChannel.open(group).bind(new InetSocketAddress("localhost", 9999));
System.out.println("BOUND");
ssc.accept(ssc, handler);
group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
}