Example usage for io.netty.channel ChannelFuture syncUninterruptibly

List of usage examples for io.netty.channel ChannelFuture syncUninterruptibly

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture syncUninterruptibly.

Prototype

@Override
    ChannelFuture syncUninterruptibly();

Source Link

Usage

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    //netty4/*from w  w  w  .j  a  v  a  2 s  .c  om*/
    bootstrap = new ServerBootstrap();
    //1?
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    //       cpu*2 
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            //                
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();

    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override//from  ww w  .j  a va  2s  .  co m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java

License:Apache License

/**
 * Shutdown method for {@link GemFireRedisServer}. This closes the {@link Cache},
 * interrupts all execution and forcefully closes all connections.
 *///from w  w w  . jav  a  2 s. c  o  m
public synchronized void shutdown() {
    if (!shutdown) {
        if (logger.infoEnabled())
            logger.info("GemFireRedisServer shutting down");
        ChannelFuture closeFuture = this.serverChannel.closeFuture();
        Future<?> c = workerGroup.shutdownGracefully();
        Future<?> c2 = bossGroup.shutdownGracefully();
        this.serverChannel.close();
        c.syncUninterruptibly();
        c2.syncUninterruptibly();
        this.regionCache.close();
        if (mainThread != null)
            mainThread.interrupt();
        for (ScheduledFuture<?> f : this.expirationFutures.values())
            f.cancel(true);
        this.expirationFutures.clear();
        this.expirationExecutor.shutdownNow();
        closeFuture.syncUninterruptibly();
        shutdown = true;
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.nonrpc.StatusClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("usage: <serverHostname> <serverPort>");
        System.exit(-1);//from   w  w w.  j a  v a 2s  . c o m
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);

    PeerInfo server = new PeerInfo(serverHostname, serverPort);

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setRpcServerCallExecutor(new ThreadPoolCallExecutor(3, 10));

        // RPC payloads are uncompressed when logged - so reduce logging
        CategoryPerServiceLogger logger = new CategoryPerServiceLogger();
        logger.setLogRequestProto(false);
        logger.setLogResponseProto(false);
        clientFactory.setRpcLogger(logger);

        final RpcCallback<PingPong.Status> serverStatusCallback = new RpcCallback<PingPong.Status>() {

            @Override
            public void run(PingPong.Status parameter) {
                log.info("Received " + parameter);
            }

        };

        // Set up the event pipeline factory.
        // setup a RPC event listener - it just logs what happens
        RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();

        final RpcConnectionEventListener listener = new RpcConnectionEventListener() {

            @Override
            public void connectionReestablished(RpcClientChannel clientChannel) {
                log.info("connectionReestablished " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }

            @Override
            public void connectionOpened(RpcClientChannel clientChannel) {
                log.info("connectionOpened " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }

            @Override
            public void connectionLost(RpcClientChannel clientChannel) {
                log.info("connectionLost " + clientChannel);
            }

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }
        };
        rpcEventNotifier.addEventListener(listener);
        clientFactory.registerConnectionEventListener(rpcEventNotifier);

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup workers = new NioEventLoopGroup(16,
                new RenamingThreadFactoryProxy("workers", Executors.defaultThreadFactory()));
        bootstrap.group(workers);
        bootstrap.handler(clientFactory);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
        bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

        RpcClientConnectionWatchdog watchdog = new RpcClientConnectionWatchdog(clientFactory, bootstrap);
        rpcEventNotifier.addEventListener(watchdog);
        watchdog.start();

        CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
        shutdownHandler.addResource(workers);

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            PingPong.Status clientStatus = PingPong.Status.newBuilder()
                    .setMessage("Client " + channel + " OK@" + System.currentTimeMillis()).build();

            ChannelFuture oobSend = channel.sendOobMessage(clientStatus);
            if (!oobSend.isDone()) {
                log.info("Waiting for completion.");
                oobSend.syncUninterruptibly();
            }
            if (!oobSend.isSuccess()) {
                log.warn("OobMessage send failed.", oobSend.cause());
            }

            Thread.sleep(1000);

        }

    } finally {
        System.exit(0);
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.nonrpc.StatusServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("usage: <serverHostname> <serverPort>");
        System.exit(-1);/*ww  w.  j  ava 2s  .c o  m*/
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);

    PeerInfo serverInfo = new PeerInfo(serverHostname, serverPort);

    // RPC payloads are uncompressed when logged - so reduce logging
    CategoryPerServiceLogger logger = new CategoryPerServiceLogger();
    logger.setLogRequestProto(false);
    logger.setLogResponseProto(false);

    // Configure the server.
    DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(10, 10);
    serverFactory.setRpcServerCallExecutor(rpcExecutor);
    serverFactory.setLogger(logger);

    final RpcCallback<PingPong.Status> clientStatusCallback = new RpcCallback<PingPong.Status>() {

        @Override
        public void run(PingPong.Status parameter) {
            log.info("Received " + parameter);
        }

    };
    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {

        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("connectionReestablished " + clientChannel);

            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("connectionOpened " + clientChannel);

            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("connectionLost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("connectionChanged " + clientChannel);
            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    serverFactory.registerConnectionEventListener(rpcEventNotifier);

    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup boss = new NioEventLoopGroup(2,
            new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory()));
    EventLoopGroup workers = new NioEventLoopGroup(16,
            new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory()));
    bootstrap.group(boss, workers);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());

    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(boss);
    shutdownHandler.addResource(workers);
    shutdownHandler.addResource(rpcExecutor);

    // Bind and start to accept incoming connections.
    bootstrap.bind();
    log.info("Serving " + bootstrap);

    while (true) {

        List<RpcClientChannel> clients = serverFactory.getRpcClientRegistry().getAllClients();
        for (RpcClientChannel client : clients) {

            PingPong.Status serverStatus = PingPong.Status.newBuilder()
                    .setMessage("Server " + serverFactory.getServerInfo() + " OK@" + System.currentTimeMillis())
                    .build();

            ChannelFuture oobSend = client.sendOobMessage(serverStatus);
            if (!oobSend.isDone()) {
                log.info("Waiting for completion.");
                oobSend.syncUninterruptibly();
            }
            if (!oobSend.isSuccess()) {
                log.warn("OobMessage send failed.", oobSend.cause());
            }

        }
        log.info("Sleeping 5s before sending serverStatus to all clients.");

        Thread.sleep(5000);
    }
}

From source file:io.lettuce.core.protocol.DefaultEndpoint.java

License:Apache License

/**
 * Reset the command-handler to the initial not-connected state.
 *//*from   w w w .  ja  va2 s.  com*/
public void initialState() {

    commandBuffer.clear();

    Channel currentChannel = this.channel;
    if (currentChannel != null) {

        ChannelFuture close = currentChannel.close();
        if (currentChannel.isOpen()) {
            close.syncUninterruptibly();
        }
    }
}

From source file:io.undertow.websockets.utils.WebSocketTestClient.java

License:Open Source License

/**
 * Connect the WebSocket client/*from  w  w w .  jav a  2  s  .  c om*/
 *
 * @throws Exception
 */
public WebSocketTestClient connect() throws Exception {
    String protocol = uri.getScheme();
    if (!"ws".equals(protocol)) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    }
    final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, version,
            null, false, new DefaultHttpHeaders());

    EventLoopGroup group = new NioEventLoopGroup();
    final CountDownLatch handshakeLatch = new CountDownLatch(1);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel channel) throws Exception {

            ChannelPipeline p = channel.pipeline();
            p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                    new WSClientHandler(handshaker, handshakeLatch));
        }
    });

    // Connect
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(uri.getHost(), uri.getPort()));
    future.syncUninterruptibly();

    ch = future.channel();

    handshaker.handshake(ch).syncUninterruptibly();
    handshakeLatch.await();

    return this;
}

From source file:org.aaron.sms.broker.AbstractSMSBrokerServer.java

License:Open Source License

@PostConstruct
public void init() {
    if (!isAvailable()) {
        log.warn("{} is not available, not staring server", getClass().getSimpleName());
    } else {/* w w w .  j av a  2 s . c  o  m*/
        InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());

        final ChannelInitializer<Channel> childHandler = new SMSProtocolChannelInitializer(ServerHandler::new,
                SMSProtocol.ClientToBrokerMessage.getDefaultInstance());

        final ChannelFuture channelFuture = doBootstrap(childHandler);

        final Channel serverChannel = channelFuture.syncUninterruptibly().channel();
        allChannels.add(serverChannel);

        log.info("listening on {} ({})", serverChannel.localAddress(), getEventLoopGroup());
    }
}

From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Wraps given {@link ChannelFuture} to ensure the event loops
 * shut down gracefully./* www.j a v a  2 s .  c  o m*/
 * @param target the original channel future.
 * @param bossGroup the boss group.
 * @param workerGroup the worker group.
 * @return the wrapped future.
 */
@NotNull
protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup,
        @NotNull final NioEventLoopGroup workerGroup) {
    return new ChannelFuture() {
        @Override
        public Channel channel() {
            return target.channel();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.addListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.addListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.removeListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.removeListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture sync() throws InterruptedException {
            ChannelFuture result = null;

            try {
                result = target.sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }

            return result;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture syncUninterruptibly() {
            return target.syncUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture await() throws InterruptedException {
            return target.await();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture awaitUninterruptibly() {
            return target.awaitUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isSuccess() {
            return target.isSuccess();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancellable() {
            return target.isCancellable();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Throwable cause() {
            return target.cause();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException {
            return target.await(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeoutMillis) throws InterruptedException {
            return target.await(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) {
            return target.awaitUninterruptibly(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeoutMillis) {
            return target.awaitUninterruptibly(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void getNow() {
            return target.getNow();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return target.cancel(mayInterruptIfRunning);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancelled() {
            return target.isCancelled();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isDone() {
            return target.isDone();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            return target.get();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get(final long timeout, @NotNull final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return target.get(timeout, unit);
        }
    };
}

From source file:org.apache.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

/**
 * Init and start netty server/*w ww  . j av a 2 s . co m*/
 *
 * @throws Throwable
 */
@Override
protected void doOpen() throws Throwable {
    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    // FIXME: should we use getTimeout()?
                    int idleTimeout = UrlUtils.getIdleTimeout(getUrl());
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("server-idle-handler",
                                    new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS))
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}