Example usage for io.netty.channel ChannelFuture sync

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

Introduction

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

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

From source file:org.jupiter.registry.ConfigClient.java

License:Apache License

/**
 * ConfigClient??, async?// w ww. java2  s .  c om
 */
@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(),
            address.getPort());

    // ?watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, null) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] { this, new IdleStateChecker(timer, 0, WRITER_IDLE_TIME_SECONDS, 0),
                    idleStateTrigger, new MessageDecoder(), encoder, ackEncoder, handler };
        }
    };
    watchdog.setReconnect(true);

    try {
        ChannelFuture future;
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // ?synchronized???
        future.sync();
        channel = future.channel();
    } catch (Throwable t) {
        throw new ConnectFailedException("connects to [" + address + "] fails", t);
    }

    return new JConnection(address) {

        @Override
        public void setReconnect(boolean reconnect) {
            watchdog.setReconnect(reconnect);
        }
    };
}

From source file:org.jupiter.registry.DefaultRegistry.java

License:Apache License

/**
 * ConfigClient??, async?/*w  w w .ja v  a2s  . c  o  m*/
 */
@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(),
            address.getPort());

    // ?watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, null) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] { this,
                    new IdleStateChecker(timer, 0, JConstants.WRITER_IDLE_TIME_SECONDS, 0), idleStateTrigger,
                    new MessageDecoder(), encoder, ackEncoder, handler };
        }
    };
    watchdog.start();

    try {
        ChannelFuture future;
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // ?synchronized???
        future.sync();
        channel = future.channel();
    } catch (Throwable t) {
        throw new ConnectFailedException("connects to [" + address + "] fails", t);
    }

    return new JConnection(address) {

        @Override
        public void setReconnect(boolean reconnect) {
            if (reconnect) {
                watchdog.start();
            } else {
                watchdog.stop();
            }
        }
    };
}

From source file:org.jupiter.transport.netty.JNettyTcpConnector.java

License:Apache License

@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();//from  w  w w .ja v a  2  s.c  o  m

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(),
            address.getPort());
    final JChannelGroup group = group(address);

    // ?watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, group) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] { this,
                    new IdleStateChecker(timer, 0, JConstants.WRITER_IDLE_TIME_SECONDS, 0), idleStateTrigger,
                    new ProtocolDecoder(), encoder, handler };
        }
    };
    watchdog.start();

    ChannelFuture future;
    try {
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // ?synchronized???
        if (!async) {
            future.sync();
        }
    } catch (Throwable t) {
        throw new ConnectFailedException("connects to [" + address + "] fails", t);
    }

    return new JNettyConnection(address, future) {

        @Override
        public void setReconnect(boolean reconnect) {
            if (reconnect) {
                watchdog.start();
            } else {
                watchdog.stop();
            }
        }
    };
}

From source file:org.jupiter.transport.netty.JNettyUdtConnector.java

License:Apache License

@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();//from  ww w.  ja  v a 2s. com

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(),
            address.getPort());
    final JChannelGroup group = group(address);

    // ?watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, group) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] { this, new IdleStateChecker(timer, 0, WRITER_IDLE_TIME_SECONDS, 0),
                    idleStateTrigger, new ProtocolDecoder(), encoder, handler };
        }
    };
    watchdog.setReconnect(true);

    ChannelFuture future;
    try {
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<UdtChannel>() {

                @Override
                protected void initChannel(UdtChannel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // ?synchronized???
        if (!async) {
            future.sync();
        }
    } catch (Throwable t) {
        throw new ConnectFailedException("connects to [" + address + "] fails", t);
    }

    return new JNettyConnection(address, future) {

        @Override
        public void setReconnect(boolean reconnect) {
            watchdog.setReconnect(reconnect);
        }
    };
}

From source file:org.kaazing.messaging.driver.transport.netty.udp.NettySendingTransport.java

License:Apache License

@Override
public void submit(DriverMessage driverMessage) {
    DatagramPacket nettyMessage = tlNettyMessage.get();
    nettyMessage.content().retain();//from  w ww .j a  va  2 s  .  co  m

    //TODO(JAF): Avoid making a new byte array with each send
    byte[] bytesToSend = new byte[driverMessage.getBufferLength()];
    driverMessage.getBuffer().getBytes(driverMessage.getBufferOffset(), bytesToSend);
    nettyMessage.content().setBytes(0, bytesToSend);
    nettyMessage.content().writerIndex(bytesToSend.length);

    ChannelFuture future = sendingChannel.writeAndFlush(nettyMessage);
    try {
        if (future.sync().await(1000) == false) {
            LOGGER.debug("Timed out sending message");
        }

    } catch (InterruptedException e) {
        LOGGER.debug("Interrupted while sending message");
    }
}

From source file:org.kualigan.maven.plugins.AbstractStartRedisMojo.java

License:Apache License

/**
 * Start the redis server//from w w w .  j av a 2 s .  co m
 *
 * @param isForked is a {@link Boolean} determing whether to fork the redis server or not.
 */
public void start(final Boolean isForked) throws InterruptedException {
    // Only execute the command handler in a single thread
    final RedisCommandHandler commandHandler = new RedisCommandHandler(new SimpleRedisServer());

    // Configure the server.
    final ServerBootstrap b = new ServerBootstrap();
    final DefaultEventExecutorGroup group = new DefaultEventExecutorGroup(1);
    getPluginContext().put(REDIS_GROUP_CONTEXT_PROPERTY_NAME, group);

    try {
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(getPort())
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        final ChannelPipeline p = ch.pipeline();
                        p.addLast(new RedisCommandDecoder());
                        p.addLast(new RedisReplyEncoder());
                        p.addLast(group, commandHandler);
                    }
                });

        final StringBuffer message = new StringBuffer();

        // Start the server.
        if (isForked) {
            message.append("Forking Redis");
        } else {
            message.append("Starting Redis");
        }

        message.append("(port=").append(getPort()).append(") server...");
        getLog().info(message.toString());

        final ChannelFuture f = b.bind();

        // Wait until the server socket is closed.
        if (!isForked) {
            f.sync();
            f.channel().closeFuture().sync();
        }
    } finally {
        // Shut down all event loops to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:org.maxur.clitelnetclient.Sender.java

License:Apache License

void send() throws InterruptedException {
    final EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w  w  w.  j a  v a2  s .c o  m
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer());
        final Channel channel = bootstrap.connect(host, port).sync().channel();
        final ChannelFuture lastWriteFuture = channel.writeAndFlush(command + EOL);
        channel.closeFuture().sync();
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();

    }
}

From source file:org.mobicents.media.server.ctrl.rtsp.stack.RtspClientStackImpl.java

License:Open Source License

public void start() throws IOException {

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);/*from  ww w  .jav  a 2s  .c om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            // httpResponse??HttpResponseDecoder?
            ch.pipeline().addLast(new RtspResponseDecoder());
            // ??httprequest?HttpRequestEncoder?
            ch.pipeline().addLast(new RtspRequestEncoder());
            // ch.pipeline().addLast(new HttpObjectAggregator(1024 * 64));
            ch.pipeline().addLast("handler", new RtspResponseHandler(RtspClientStackImpl.this));
        }
    });

    // Start the client.
    ChannelFuture f = b.connect(getHost(), getPort());
    try {
        f.sync();
        channel = f.channel();

        InetSocketAddress bindAddress = new InetSocketAddress(this.host, this.port);

        logger.info("Mobicents RTSP Client started and bound to " + bindAddress.toString());

    } catch (InterruptedException e) {
        throw new IOException(f.cause());
    }
}

From source file:org.mobicents.media.server.io.network.netty.UdpNetworkManagerTest.java

License:Open Source License

@Test
public void testBindUdpChannel() {
    // given//from w  w  w  .  j a v a2  s .  c om
    PortManager ports = mock(PortManager.class);
    ChannelHandler handler = mock(ChannelHandler.class);
    NetworkManager manager = new UdpNetworkManager("127.0.0.1", ports);

    // when - activate manager and bind channel
    when(ports.next()).thenReturn(65530);
    manager.activate();

    ChannelFuture future = manager.bindChannel(handler);
    Channel channel = future.channel();

    try {
        future.sync();
    } catch (InterruptedException e) {
        fail();
    }

    // then
    assertTrue(manager.isActive());
    assertTrue(future.isSuccess());
    assertNotNull(channel);
    assertTrue(channel.isOpen());
    assertTrue(channel.isActive());
    assertEquals(new InetSocketAddress("127.0.0.1", 65530), channel.localAddress());

    // when - deactivate manager
    manager.deactivate();

    // then
    assertFalse(manager.isActive());
    assertFalse(channel.isOpen());
    assertFalse(channel.isActive());
}

From source file:org.mobicents.media.server.rtsp.stack.RtspClientStackImpl.java

License:Open Source License

public void connect() throws IOException {

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);/*from   w  w  w  .j a  va 2 s  . c o  m*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            // ??httpResponse???HttpResponseDecoder?
            ch.pipeline().addLast(new RtspResponseDecoder());
            // ?ttprequest?HttpRequestEncoder?
            ch.pipeline().addLast(new RtspRequestEncoder());
            // ch.pipeline().addLast(new HttpObjectAggregator(1024 * 64));
            ch.pipeline().addLast("handler", new RtspResponseHandler(RtspClientStackImpl.this));
        }
    });

    // Start the client.
    ChannelFuture f = b.connect(getHost(), getPort());
    try {
        f.sync();
        channel = f.channel();

        InetSocketAddress bindAddress = new InetSocketAddress(this.host, this.port);

        logger.info("Mobicents RTSP Client started and bound to " + bindAddress.toString());

        RtspResponseHandler handler = (RtspResponseHandler) f.channel().pipeline().get("handler");
        handler.connect();
    } catch (InterruptedException e) {
        throw new IOException(f.cause());
    }
}