Java 类java.nio.channels.AsynchronousServerSocketChannel 实例源码

项目:tephra    文件:AioServerImpl.java   
@Override
public void listen(int thread, int port, AioServerListener listener) {
    this.port = port;
    this.listener = listener;
    try {
        channelGroup = AsynchronousChannelGroup.withFixedThreadPool(thread, Executors.defaultThreadFactory());
        serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);
        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.accept(null, this);

        if (logger.isInfoEnable())
            logger.info("启动AIO监听[{}]服务。", port);
    } catch (IOException e) {
        logger.warn(e, "启动AIO监听[{}]服务时发生异常!", port);
    }
}
项目:parallelism-benchmarks    文件:FountainSocketBenchmark.java   
public Runnable serverAsyncRunnable(int byteCount, int numClients) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    AsynchronousServerSocketChannel socket = AsynchronousServerSocketChannel.open(asynChanGroupFJP)
                            .bind(null);
//                  System.out.println("bound");
                    SocketAddress localAddress = socket.getLocalAddress();
                    List<ForkJoinTask<?>> startClientsThreadAsync = startClientsThreadAsync(localAddress, numClients);
                    socket.accept(numClients, acceptCompletionHandler(byteCount, socket));
                    for (ForkJoinTask<?> f:startClientsThreadAsync) {
                        f.join();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        };
    }
项目:parallelism-benchmarks    文件:FountainSocketBenchmark.java   
private CompletionHandler<AsynchronousSocketChannel, Integer> acceptCompletionHandler(
            int byteCount, AsynchronousServerSocketChannel socket) {
        return new CompletionHandler<AsynchronousSocketChannel, Integer>() {
            public void completed(
                    AsynchronousSocketChannel ch,
                    Integer acceptsToGo) {
                acceptsToGo = acceptsToGo-1;
//              System.out.println("server accepted, to go = " + acceptsToGo);
                writeStuffThreadAsync(socket, ch, byteCount, acceptsToGo);
                if (acceptsToGo > 0) {
                    socket.accept(acceptsToGo, acceptCompletionHandler(byteCount, socket));
                }
            }
            public void failed(Throwable exc, Integer attachment) {
                exc.printStackTrace();
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
    }
项目:jephyr    文件:NioSocketImpl.java   
@Override
protected void listen(int backlog) throws IOException {
    AsynchronousServerSocketChannel channel = AsynchronousServerSocketChannel.open();
    try {
        if (localAddress != null) {
            channel.bind(new InetSocketAddress(localAddress, localport), backlog);
            localport = ((InetSocketAddress) channel.getLocalAddress()).getPort();
        }
    } catch (IOException e) {
        try {
            channel.close();
        } catch (IOException suppressed) {
            e.addSuppressed(suppressed);
        }
        throw e;
    }
    this.channel = channel;
}
项目:javase-study    文件:AsynchronousServerSocketMain.java   
public static void main(String[] args) throws IOException, ExecutionException,
          InterruptedException, TimeoutException {
    //打开 AsychronousServerSocketChannel 并将其绑定到类似于 ServerSocketChannel 的地址
    //方法 bind() 将一个套接字地址作为其参数。找到空闲端口的便利方法是传递一个 null 地址,它会自动将套接字绑定到本地主机地址,并使用空闲的 临时 端口。
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(null);
    //告诉通道接受一个连接
    Future<AsynchronousSocketChannel> future = server.accept();

//    利用 Future 对象,当前线程可阻塞来等待结果:
    AsynchronousSocketChannel worker = future.get();
    //超时
    //AsynchronousSocketChannel worker = future.get(10, TimeUnit.SECONDS);
    //取消
//    if (!future.isDone()) {
//      future.cancel(true);//cancel() 方法可利用一个布尔标志来指出执行接受的线程是否可被中断
//    }
//
//// read a message from the client
    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    worker.read(readBuffer).get(10, TimeUnit.SECONDS);
    System.out.println("Message: " + new String(readBuffer.array()));
  }
项目:jane    文件:TcpManager.java   
public synchronized void startServer(SocketAddress addr, Object attachment, AsynchronousChannelGroup group)
{
    stopServer();
    try
    {
        _acceptor = AsynchronousServerSocketChannel.open(group);
        int backlog = onAcceptorCreated(_acceptor, attachment);
        if(backlog >= 0)
        {
            _acceptor.bind(addr, backlog);
            beginAccept();
            return;
        }
    }
    catch(Throwable e)
    {
        doException(null, e);
    }
    stopServer();
}
项目:sonews    文件:AsynchronousNNTPDaemon.java   
@Override
public void run() {
    try {
        final int workerThreads = Math.max(4, 2 *
                Runtime.getRuntime().availableProcessors());
        channelGroup = AsynchronousChannelGroup.withFixedThreadPool(
                workerThreads, Executors.defaultThreadFactory());

        serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);
        serverSocketChannel.bind(new InetSocketAddress(port));

        serverSocketChannel.accept(null,
                new AcceptCompletionHandler(serverSocketChannel));

        channelGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    } catch(IOException | InterruptedException ex) {
        Log.get().log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
}
项目:io-comparison    文件:AioServer.java   
@Override
public void start() throws IOException, InterruptedException {
    if (running.compareAndSet(false, true)) {
        final CountDownLatch latch = new CountDownLatch(1);

        final AsynchronousServerSocketChannel ssc = AsynchronousServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(port));

        ssc.accept(this, new AcceptHandler());

        connectionLatch = latch;
        serverSocketChannel = ssc;
    }
}
项目:mycat-src-1.6.1-RELEASE    文件:AIOAcceptor.java   
public AIOAcceptor(String name, String ip, int port,
        FrontendConnectionFactory factory, AsynchronousChannelGroup group)
        throws IOException {
    this.name = name;
    this.port = port;
    this.factory = factory;
    serverChannel = AsynchronousServerSocketChannel.open(group);
    /** 设置TCP属性 */
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024 * 16 * 2);
    // backlog=100
    serverChannel.bind(new InetSocketAddress(ip, port), 100);
}
项目:circus-train    文件:ServerSocketRule.java   
public ServerSocketRule() {
  try {
    listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(0));
    address = (InetSocketAddress) listener.getLocalAddress();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:netty_op    文件:AsyncTimeServerHandler.java   
public AsyncTimeServerHandler(int port){
    this.port = port;
    try{
        //创建AsyncTimeServerHandler并启动服务端Socket
        asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
        asynchronousServerSocketChannel.bind(new InetSocketAddress(this.port));
        System.out.println("服务器已启动, 端口号: " + port);
    }catch(Exception e){
        e.printStackTrace();
    }
}
项目:samplecode    文件:Server.java   
public AsyncServerHandler(int port) {
    try {
        // 创建服务端通道
        channel = AsynchronousServerSocketChannel.open();
        // 绑定端口
        channel.bind(new InetSocketAddress(port));
        System.out.println("服务器已启动,端口号:" + port);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:waggle-dance    文件:ServerSocketRule.java   
public ServerSocketRule() {
  try {
    listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(0));
    address = (InetSocketAddress) listener.getLocalAddress();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:waterwave    文件:AioServer.java   
private AsynchronousServerSocketChannel createListener(AsynchronousChannelGroup channelGroup) throws IOException {
    final AsynchronousServerSocketChannel listener = openChannel(channelGroup);
    listener.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    listener.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    listener.bind(new InetSocketAddress(port), 0);
    return listener;
}
项目:talent-aio    文件:AioServer.java   
public void start(String serverIp, int serverPort) throws IOException
{
    this.serverNode = new Node(serverIp, serverPort);
    ExecutorService groupExecutor = serverGroupContext.getGroupExecutor();

    AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(groupExecutor);
    serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);

    serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 64 * 1024);

    InetSocketAddress listenAddress = null;

    if (StringUtils.isBlank(serverIp))
    {
        listenAddress = new InetSocketAddress(serverPort);
    } else
    {
        listenAddress = new InetSocketAddress(serverIp, serverPort);
    }

    serverSocketChannel.bind(listenAddress, 0);

    AcceptCompletionHandler<SessionContext, P, R> acceptCompletionHandler = serverGroupContext.getAcceptCompletionHandler();
    serverSocketChannel.accept(this, acceptCompletionHandler);

    System.out.println("start server on " + this.serverNode);
}
项目:talent-aio    文件:AcceptCompletionHandler.java   
/** 
 * @see java.nio.channels.CompletionHandler#failed(java.lang.Throwable, java.lang.Object)
 * 
 * @param exc
 * @param aioServer
 * @重写人: tanyaowu
 * @重写时间: 2016年11月16日 下午1:28:05
 * 
 */
@Override
public void failed(Throwable exc, AioServer<SessionContext, P, R> aioServer)
{
    AsynchronousServerSocketChannel serverSocketChannel = aioServer.getServerSocketChannel();
    serverSocketChannel.accept(aioServer, this);

    log.error("[" + aioServer.getServerNode() + "]监听出现异常", exc);

}
项目:xxl-incubator    文件:AsyncServerHandler.java   
public AsyncServerHandler(int port) {
    try {
        //创建服务端通道
        channel = AsynchronousServerSocketChannel.open();
        //绑定端口
        channel.bind(new InetSocketAddress(port));
        System.out.println("服务器已启动,端口号:" + port);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:xtext-languageserver-example    文件:RunServer.java   
static <T> Launcher<T> createSocketLauncher(Object localService, Class<T> remoteInterface, SocketAddress socketAddress, ExecutorService executorService, Function<MessageConsumer, MessageConsumer> wrapper) throws IOException {
    AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open().bind(socketAddress);
    AsynchronousSocketChannel socketChannel;
    try {
        socketChannel = serverSocket.accept().get();
        return Launcher.createIoLauncher(localService, remoteInterface, Channels.newInputStream(socketChannel), Channels.newOutputStream(socketChannel), executorService, wrapper);
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}
项目:netty-book    文件:AsyncTimeServerHandler.java   
public AsyncTimeServerHandler(int port) {
this.port = port;
try {
    asynchronousServerSocketChannel = AsynchronousServerSocketChannel
        .open();
    asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
    System.out.println("The time server is start in port : " + port);
} catch (IOException e) {
    e.printStackTrace();
}
   }
项目:hologram    文件:TcpReceiverConnectorNio2.java   
public void run() {
    while (isRunning) {
        try {
            SocketAddress address = new InetSocketAddress("localhost", mainPort);
            AsynchronousServerSocketChannel channel = AsynchronousServerSocketChannel.open().bind(address);

            channel.accept(null, null);
        } catch(Exception e) {
            System.err.println(e);
        }
    }
}
项目:hope-tactical-equipment    文件:AsyncTimeServerHandler.java   
public AsyncTimeServerHandler(int port) {
    this.port = port;
    try {
        asynchronousServerSocketChannel = AsynchronousServerSocketChannel
                .open();
        asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
        System.out.println("The time server is start in port : " + port);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:compfut    文件:AsyncServer.java   
public static void main(String[] args) throws Exception {
    final AsynchronousServerSocketChannel ssc =
            AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("localhost", 9999));
    Future<AsynchronousSocketChannel> accepted = ssc.accept();
    AsynchronousSocketChannel sc2 = accepted.get();

    ByteBuffer bb = ByteBuffer.allocateDirect(4096);
    Future<Integer> readFuture = sc2.read(bb);
}
项目:windup-rulesets    文件:SocketCommunication.java   
public static void main(String argv[]) {
    Socket s = new Socket();
    s.getInputStream();
    MulticastSocket ms = new MulticastSocket();
    ms.close();
    DatagramSocket ds = new DatagramSocket();
    ds.close();
    InetSocketAddress isa = new MyInetSocketAddress();
    isa.isUnresolved();
    NetworkChannel nc = new MyNetworkChannel();
    nc.getLocalAddress();
    MulticastChannel mc = new MyMulticastChannel();
    mc.close();
    DatagramChannel dc =  new MyDatagramChannel();
    dc.getLocalAddress();
    AsynchronousSocketChannel asc = new MyAsynchronousSocketChannel();
    asc.getLocalAddress();
    SocketChannel sc = new MySocketChannel();
    sc.isConnected();

    ServerSocket ss = new ServerSocket();
    ss.close();
    AsynchronousServerSocketChannel assd = new MyAsynchronousServerSocketChannel();
    assd.getLocalAddress();
    ServerSocketChannel ssc = new MyServerSocketChannel();
    ssc.getLocalAddress();
}
项目:EasySocket    文件:SocketServer.java   
public void start() throws IOException {
    int initialSize = Runtime.getRuntime().availableProcessors();
    AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup
            .withCachedThreadPool(Executors.newCachedThreadPool(),
                    initialSize);
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel
            .open(channelGroup);
    server.bind(new InetSocketAddress(port));

    this.pendingAccept();
    logger.debug("server started at port " + this.port);
}
项目:Tatala-RPC    文件:AioSocketServer.java   
public void setUpHandlers() {
    try {
        AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup.withFixedThreadPool(poolSize, Executors.defaultThreadFactory());
        serverSocketChannel = AsynchronousServerSocketChannel.open(asyncChannelGroup).bind(new InetSocketAddress(listenPort));
        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

        log.info("** " + poolSize + " handler thread has been setup! **");
        log.info("** Socket Server has been startup, listen port is " + listenPort + "! **");
    } catch (IOException e) {
        log.error("setUpHandlers error: ", e);
    }
}
项目:Tatala-RPC    文件:AioSocketServer.java   
public void setUpHandlers() {
    try {
        AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup.withFixedThreadPool(poolSize, Executors.defaultThreadFactory());
        serverSocketChannel = AsynchronousServerSocketChannel.open(asyncChannelGroup).bind(new InetSocketAddress(listenPort));
        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    } catch (IOException e) {
        e.printStackTrace();
    }
    log.info("** " + poolSize + " handler thread has been setup! **");
    log.info("** Socket Server has been startup, listen port is " + listenPort + "! **");
}
项目:Tatala-RPC    文件:AioSocketServer.java   
public void setUpHandlers() {
    try {
        AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup
                .withFixedThreadPool(poolSize,Executors.defaultThreadFactory());
        serverSocketChannel = AsynchronousServerSocketChannel
                .open(asyncChannelGroup).bind(new InetSocketAddress(listenPort));
        serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        //serverSocketChannel.setOption(StandardSocketOption.TCP_NODELAY, true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    log.info("** " + poolSize + " handler thread has been setup! **");
    log.info("** Socket Server has been startup, listen port is " + listenPort + "! **");
}
项目:openclouddb    文件:NIOAcceptor.java   
public NIOAcceptor(String name, String ip, int port,
        FrontendConnectionFactory factory, AsynchronousChannelGroup group)
        throws IOException {
    this.name = name;
    this.port = port;
    this.factory = factory;
    serverChannel = AsynchronousServerSocketChannel.open(group);
    /** 设置TCP属性 */
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    // backlog=100
    serverChannel.bind(new InetSocketAddress(ip, port), 100);
}
项目:openclouddb    文件:NIOAcceptor.java   
public NIOAcceptor(String name, String ip,int port,
        FrontendConnectionFactory factory, AsynchronousChannelGroup group)
        throws IOException {
    this.name=name;
    this.port = port;
    this.factory = factory;
    serverChannel = AsynchronousServerSocketChannel.open(group);
    /** 设置TCP属性 */
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    // backlog=100
    serverChannel.bind(new InetSocketAddress(ip,port), 100);
}
项目:Java-Conquer-Server    文件:AbstractServer.java   
/**
 * @param local The socket address that the server is bound to
 * @throws IOException when failing to start the server
 */
protected AbstractServer(SocketAddress local) throws IOException {
    this.executor = Executors.newCachedThreadPool();
    this.channelGroup = AsynchronousChannelGroup.withThreadPool(executor);
    this.listener = AsynchronousServerSocketChannel
            .open(channelGroup)
            .setOption(StandardSocketOptions.SO_REUSEADDR, true)
            .bind(local);
    this.run();
    this.listening();
}
项目:jane    文件:TcpManager.java   
/**
 * 停止服务器监听. 但不断开已建立的连接
 */
public synchronized void stopServer()
{
    AsynchronousServerSocketChannel acceptor = _acceptor;
    if(acceptor != null)
    {
        _acceptor = null;
        closeChannel(acceptor);
    }
}
项目:jane    文件:TcpManager.java   
/**
 * 服务器开始监听前响应一次. 可以修改一些监听的设置
 * @param acceptor
 * @param attachment startServer传入的参数
 * @return 返回>=0表示监听的backlog值(0表示取默认值);返回<0表示关闭服务器监听
 */
@SuppressWarnings("static-method")
public int onAcceptorCreated(AsynchronousServerSocketChannel acceptor, Object attachment) throws IOException
{
    acceptor.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    acceptor.setOption(StandardSocketOptions.SO_RCVBUF, TcpSession.DEF_RECV_SOBUF_SIZE);
    return 0;
}
项目:openclouddb    文件:NIOAcceptor.java   
public NIOAcceptor(String name, String ip, int port,
        FrontendConnectionFactory factory, AsynchronousChannelGroup group)
        throws IOException {
    this.name = name;
    this.port = port;
    this.factory = factory;
    serverChannel = AsynchronousServerSocketChannel.open(group);
    /** 设置TCP属性 */
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    // backlog=100
    serverChannel.bind(new InetSocketAddress(ip, port), 100);
}
项目:openclouddb    文件:NIOAcceptor.java   
public NIOAcceptor(String name, String ip,int port,
        FrontendConnectionFactory factory, AsynchronousChannelGroup group)
        throws IOException {
    this.name=name;
    this.port = port;
    this.factory = factory;
    serverChannel = AsynchronousServerSocketChannel.open(group);
    /** 设置TCP属性 */
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);
    // backlog=100
    serverChannel.bind(new InetSocketAddress(ip,port), 100);
}
项目:portainer-agent    文件:AcceptHandler.java   
AcceptHandler(AsynchronousServerSocketChannel serverSocketChannel) {
  this.serverSocketChannel = serverSocketChannel;
}
项目:multithread    文件:AIOEchoServer.java   
public AIOEchoServer() throws IOException {
    //绑定了8000端口为服务器端口,并使用AsynchronousServerSocketChannel异步Channel作为服务器,变量名为server
    server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(PORT));
}
项目:openjdk-jdk10    文件:Provider2.java   
@Override
public AsynchronousServerSocketChannel openAsynchronousServerSocketChannel
    (AsynchronousChannelGroup group) throws IOException
{
    throw new RuntimeException();
}
项目:openjdk-jdk10    文件:Provider1.java   
@Override
public AsynchronousServerSocketChannel openAsynchronousServerSocketChannel
    (AsynchronousChannelGroup group) throws IOException
{
    throw new RuntimeException();
}
项目:waterwave    文件:AioServer.java   
private AsynchronousServerSocketChannel openChannel(AsynchronousChannelGroup channelGroup) throws IOException {
    return AsynchronousServerSocketChannel.open(channelGroup);
}
项目:talent-aio    文件:AioServer.java   
/**
 * @return the serverSocketChannel
 */
public AsynchronousServerSocketChannel getServerSocketChannel()
{
    return serverSocketChannel;
}