Example usage for io.netty.channel ChannelFuture awaitUninterruptibly

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

Introduction

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

Prototype

@Override
    ChannelFuture awaitUninterruptibly();

Source Link

Usage

From source file:com.github.mrstampy.kitchensync.test.stream.ByteArrayStreamerTester.java

License:Open Source License

/**
 * Stream./*from  w w w  . j ava  2 s . com*/
 *
 * @throws Exception
 *           the exception
 */
protected void stream() throws Exception {
    for (String file : files) {
        byte[] b = getBytes(file);
        ChannelFuture future = streamer.stream(b);
        future.awaitUninterruptibly();

        log.info("Success? {}", future.isSuccess());
        BigDecimal packetLoss = (BigDecimal.ONE.subtract(new BigDecimal(received.get())
                .divide(new BigDecimal(streamer.sent()), 6, RoundingMode.HALF_UP)))
                        .multiply(new BigDecimal(100));
        log.info("Sent: {}, Received: {}, Packet loss: {} %, Concurrent threads: {}", streamer.sent(),
                received.get(), packetLoss.toPlainString(), streamer.getConcurrentThreads());

        received.set(0);
    }

    streamer.cancel();
}

From source file:com.github.mrstampy.kitchensync.test.stream.StreamerTester.java

License:Open Source License

/**
 * Stream./*from   w w w  .  j a v  a  2  s .co  m*/
 *
 * @throws InterruptedException
 *           the interrupted exception
 */
protected void stream() throws InterruptedException {
    for (int i = 0; i < 3; i++) {
        ChannelFuture future = streamer.stream();
        future.awaitUninterruptibly();

        log.info("Success? {}", future.isSuccess());
        BigDecimal packetLoss = (BigDecimal.ONE.subtract(new BigDecimal(received.get())
                .divide(new BigDecimal(streamer.size()), 6, RoundingMode.HALF_UP)))
                        .multiply(new BigDecimal(100));
        log.info("Sent: {}, Received: {}, Packet loss: {} %, Concurrent threads: {}", streamer.size(),
                received.get(), packetLoss.toPlainString(), streamer.getConcurrentThreads());
        streamer.reset();
        received.set(0);

        KiSyUtils.snooze(100);
    }

    Thread.sleep(50);
}

From source file:com.github.mrstampy.pprspray.core.streamer.util.MediaStreamerUtils.java

License:Open Source License

/**
 * Send termination event.//  w  w w.j av a2 s. c o m
 *
 * @param mediaHash
 *          the media hash
 * @param channel
 *          the channel
 * @param remote
 *          the remote
 */
public static void sendTerminationEvent(int mediaHash, KiSyChannel channel, InetSocketAddress remote) {
    if (channel == null)
        return;

    MediaFooter footer = new MediaFooter(MediaStreamType.NEGOTIATION, mediaHash);

    byte[] terminate = footer.createFooter();
    ChannelFuture cf = channel.send(terminate, remote);
    cf.awaitUninterruptibly();
}

From source file:com.hxr.javatone.concurrency.netty.official.localecho.LocalEcho.java

License:Apache License

public void run() throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(port);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {//w w w.  j  a va2 s  .  co  m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Start proxy server//from w w  w  .jav  a2  s.  c om
 * */
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
        @Override
        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(new ProxyInitializer(this));

    //bind
    ChannelFuture future = serverBootstrap.bind(_host, _port);

    //wait for the future
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.channel().closeFuture().awaitUninterruptibly();
        throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
    } else {
        _allChannels.add(future.channel());
    }
}

From source file:com.mpush.client.gateway.connection.GatewayTCPConnectionFactory.java

License:Apache License

private void addConnection(String host, int port, boolean sync) {
    ChannelFuture future = client.connect(host, port);
    future.channel().attr(attrKey).set(getHostAndPort(host, port));
    future.addListener(f -> {//from   w  w  w.  java2  s.  co m
        if (!f.isSuccess()) {
            logger.error("create gateway connection ex, host={}, port={}", host, port, f.cause());
        }
    });
    if (sync)
        future.awaitUninterruptibly();
}

From source file:com.mpush.test.client.ConnClientTestMain.java

License:Apache License

private static void testConnClient(int count, String userPrefix, int printDelay, boolean sync)
        throws Exception {
    Logs.init();//from   w  w  w . j  ava 2s . co m
    ConnClientBoot boot = new ConnClientBoot();
    boot.start().get();

    List<ServiceNode> serverList = boot.getServers();
    if (serverList.isEmpty()) {
        boot.stop();
        System.out.println("no mpush server.");
        return;
    }

    if (printDelay > 0) {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
                () -> System.err.println(ConnClientChannelHandler.STATISTICS), 3, printDelay, TimeUnit.SECONDS);
    }

    for (int i = 0; i < count; i++) {
        String clientVersion = "1.0." + i;
        String osName = "android";
        String osVersion = "1.0.1";
        String userId = userPrefix + "user-" + i;
        String deviceId = userPrefix + "test-device-id-" + i;
        byte[] clientKey = CipherBox.I.randomAESKey();
        byte[] iv = CipherBox.I.randomAESIV();

        ClientConfig config = new ClientConfig();
        config.setClientKey(clientKey);
        config.setIv(iv);
        config.setClientVersion(clientVersion);
        config.setDeviceId(deviceId);
        config.setOsName(osName);
        config.setOsVersion(osVersion);
        config.setUserId(userId);

        int L = serverList.size();
        int index = (int) ((Math.random() % L) * L);
        ServiceNode node = serverList.get(index);

        ChannelFuture future = boot.connect(node.getAttr(ATTR_PUBLIC_IP), node.getPort(), config);
        if (sync)
            future.awaitUninterruptibly();
    }
}

From source file:com.spotify.netty.handler.codec.zmtp.ZMTPTestConnector.java

License:Apache License

public boolean connectAndReceive(final String ip, final int port, final int serverType) {
    context = ZMQ.context(1);/*from w w w .  j a  v a 2s.  c o  m*/
    serverSocket = context.socket(serverType);

    preConnect(serverSocket);

    serverSocket.bind("tcp://" + ip + ":" + port);

    EventLoopGroup group = new NioEventLoopGroup();
    // Configure the client.
    final Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    final ZMTPSession session = new ZMTPSession(ZMTPConnectionType.Addressed,
                            "client".getBytes());
                    ChannelPipeline pl = ch.pipeline();
                    pl.addLast(new ZMTP10Codec(session));
                    pl.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (onMessage((ZMTPIncomingMessage) msg)) {
                                receivedMessage = true;
                                ctx.channel().close();
                            }
                        }
                    });
                }
            });

    // Start the connection attempt.
    final ChannelFuture future = bootstrap.connect(new InetSocketAddress(ip, port));

    future.awaitUninterruptibly();

    afterConnect(serverSocket, future);

    // Wait until the connection is closed or the connection attempt fails.
    future.channel().closeFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    group.shutdownGracefully();

    serverSocket.close();
    context.term();

    return receivedMessage;
}

From source file:com.springapp.mvc.netty.example.localecho.LocalEcho.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);

    EventLoopGroup serverGroup = new LocalEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {//from w  w  w  .  j a va2 s . c o m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.system.distribute.server.FileClient.java

License:Apache License

public ChannelFuture run() throws Exception {
    // Configure the server.
    final Bootstrap bootstrap = BootstrapFactory.createBootstrap(ChannelType.NIO);

    bootstrap.handler(new FileClientHandler());
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);

    try {/*  w  ww.  j a v  a 2  s. c o  m*/
        final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
        channelFuture.awaitUninterruptibly();

    } catch (InterruptedException e) {

    }

    // Start the server.
    ChannelFuture f = bootstrap.bind(port).sync();

    // Wait until the server socket is closed.
    f.channel().closeFuture().sync();
    return f;

}