首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsynchronousServerSocketChannel.accept只接受一个连接

AsynchronousServerSocketChannel.accept只接受一个连接
EN

Stack Overflow用户
提问于 2013-01-14 16:53:57
回答 1查看 1K关注 0票数 2

我有一个小型服务器设置,尝试使用基于事件的连接套接字,以便在每个传入连接上调用一个处理程序。它对第一个连接很好,但是在第一个连接之后没有新的连接被接受。

为了简单起见,我只是关闭了客户机连接。而且,是的,服务器在第一个连接之后仍在运行,它不会终止。

以下是代码:

代码语言:javascript
复制
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);

}
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-12 04:00:02

公共抽象无效接受(附件,CompletionHandler处理程序)

此方法启动一个异步操作,以接受到该通道的套接字的连接。处理程序参数是在接受连接(或操作失败)时调用的完成处理程序。传递给完成处理程序的结果是新连接的AsynchronousSocketChannel。

阅读更多这里

这意味着它初始化一个异步线程以接受传入的连接。这也意味着它将接受第一个连接,并将其转发到异步线程,然后等待更多的连接。要允许更多客户端连接,还必须在覆盖已完成的函数中调用accept方法。

以下是一个例子,

代码语言:javascript
复制
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结果。也就是说,如果你要打印出“陈”,就会产生不同的物体。

不同的客户对象

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14322927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档