我有一个小型服务器设置,尝试使用基于事件的连接套接字,以便在每个传入连接上调用一个处理程序。它对第一个连接很好,但是在第一个连接之后没有新的连接被接受。
为了简单起见,我只是关闭了客户机连接。而且,是的,服务器在第一个连接之后仍在运行,它不会终止。
以下是代码:
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);
}
}发布于 2018-03-12 04:00:02
公共抽象无效接受(附件,CompletionHandler处理程序)
此方法启动一个异步操作,以接受到该通道的套接字的连接。处理程序参数是在接受连接(或操作失败)时调用的完成处理程序。传递给完成处理程序的结果是新连接的AsynchronousSocketChannel。
阅读更多这里
这意味着它初始化一个异步线程以接受传入的连接。这也意味着它将接受第一个连接,并将其转发到异步线程,然后等待更多的连接。要允许更多客户端连接,还必须在覆盖已完成的函数中调用accept方法。
以下是一个例子,
server.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
@Override
public void completed(AsynchronousSocketChannel chan, Void attachment) {
System.out.println("Incoming connection...");
server.accept(null, this); //add this
//...应该指出,对于每个客户端,都会产生一个新的AsynchronousSocketChannel结果。也就是说,如果你要打印出“陈”,就会产生不同的物体。
https://stackoverflow.com/questions/14322927
复制相似问题