Example usage for io.netty.channel ChannelFuture channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.phei.netty.codec.msgpack.EchoServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup acceptorGroup = new NioEventLoopGroup();
    EventLoopGroup IOGroup = new NioEventLoopGroup();
    try {/*w w w .  j av  a2  s  . c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, IOGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
                        ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

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

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

From source file:com.phei.netty.codec.msgpack.EchoServerV2.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup acceptorGroup = new NioEventLoopGroup();
    EventLoopGroup IOGroup = new NioEventLoopGroup();
    try {/*  ww w  .  j  a  va 2 s .c  o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, IOGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("frameDecoder",
                                new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
                        ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
                        ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
                        ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

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

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

From source file:com.phei.netty.frame.fixedLen.EchoClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*from   w w w  . j  av  a2s.  c om*/
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:com.phei.netty.frame.fixedLen.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from  w w w. j  a v  a  2  s.com
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:com.phei.netty.protocol.http.fileServer.HttpFileServer.java

License:Apache License

public void run(final int port, final String url) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w w w .  j av a  2s  .  c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //http??
                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        //???fullhttprequestfullhttpresponse
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        //http??
                        ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        //?????
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                    }
                });
        ChannelFuture future = b.bind("192.168.1.102", port).sync();
        System.out.println(
                "HTTP??? : " + "http://192.168.1.102:" + port + url);
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.phei.netty.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO// w  ww  . j a v  a  2  s . c o  m
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //????http?
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        //1Http????HTTP?
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML?
                        //http+XML??
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(2);
    try {//from ww  w. j  av a2  s. c o  m
        final Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyThriftClientInitializer());

        // Start the connection attempt.
        ChannelFuture future = b.connect(host, port);
        ChannelFuture sync = future.sync();
        Channel ch = sync.channel();

        AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
        Attribute<String> attr = ch.attr(key);
        String andSet = attr.getAndSet(Thread.currentThread().getName());

        TMemoryBuffer transportr = new TMemoryBuffer(1024);
        TProtocol protocol = new TBinaryProtocol(transportr);
        TMultiplexedProtocol multiProtocol3 = new TMultiplexedProtocol(protocol,
                IdGenService.class.getSimpleName());
        IdGenService.Client aoClient = new IdGenService.Client(multiProtocol3);
        IdGenReq req = new IdGenReq();
        req.setTableName("t_lottery_append_task-----------");
        req.setSource(andSet);
        aoClient.send_idGen(req);
        int length = transportr.length();
        byte[] buf = new byte[length];
        transportr.read(buf, 0, length);
        System.out.println(Arrays.toString(buf));

        ChannelFuture lastWriteFuture = ch.writeAndFlush(buf);
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

        System.in.read();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Connects to the given APNs gateway on the given port.</p>
 *
 * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the
 * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection
 * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection
 * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p>
 *
 * @param host the APNs gateway to which to connect
 * @param port the port on which to connect to the APNs gateway
 *
 * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send
 * push notifications//  w ww  . j av a  2 s.  co m
 *
 * @see ApnsClient#PRODUCTION_APNS_HOST
 * @see ApnsClient#DEVELOPMENT_APNS_HOST
 * @see ApnsClient#DEFAULT_APNS_PORT
 * @see ApnsClient#ALTERNATE_APNS_PORT
 *
 * @since 0.5
 */
public Future<Void> connect(final String host, final int port) {
    final Future<Void> connectionReadyFuture;

    if (this.bootstrap.config().group().isShuttingDown() || this.bootstrap.config().group().isShutdown()) {
        connectionReadyFuture = new FailedFuture<>(GlobalEventExecutor.INSTANCE, new IllegalStateException(
                "Client's event loop group has been shut down and cannot be restarted."));
    } else {
        synchronized (this.bootstrap) {
            // We only want to begin a connection attempt if one is not already in progress or complete; if we already
            // have a connection future, just return the existing promise.
            if (this.connectionReadyPromise == null) {
                this.metricsListener.handleConnectionAttemptStarted(this);

                final ChannelFuture connectFuture = this.bootstrap.connect(host, port);
                this.connectionReadyPromise = connectFuture.channel().newPromise();

                connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise;

                            if (connectionReadyPromise != null) {
                                // This may seem spurious, but our goal here is to accurately report the cause of
                                // connection failure; if we just wait for connection closure, we won't be able to
                                // tell callers anything more specific about what went wrong.
                                connectionReadyPromise.tryFailure(future.cause());
                            }
                        }
                    }
                });

                connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        synchronized (ApnsClient.this.bootstrap) {
                            if (ApnsClient.this.connectionReadyPromise != null) {
                                // We always want to try to fail the "connection ready" promise if the connection
                                // closes; if it has already succeeded, this will have no effect.
                                ApnsClient.this.connectionReadyPromise.tryFailure(new IllegalStateException(
                                        "Channel closed before HTTP/2 preface completed."));

                                ApnsClient.this.connectionReadyPromise = null;
                            }

                            if (ApnsClient.this.reconnectionPromise != null) {
                                log.debug("Disconnected. Next automatic reconnection attempt in {} seconds.",
                                        ApnsClient.this.reconnectDelaySeconds);

                                ApnsClient.this.scheduledReconnectFuture = future.channel().eventLoop()
                                        .schedule(new Runnable() {

                                            @Override
                                            public void run() {
                                                log.debug("Attempting to reconnect.");
                                                ApnsClient.this.connect(host, port);
                                            }
                                        }, ApnsClient.this.reconnectDelaySeconds, TimeUnit.SECONDS);

                                ApnsClient.this.reconnectDelaySeconds = Math.min(
                                        ApnsClient.this.reconnectDelaySeconds, MAX_RECONNECT_DELAY_SECONDS);
                            }
                        }
                    }
                });

                this.connectionReadyPromise.addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            synchronized (ApnsClient.this.bootstrap) {
                                if (ApnsClient.this.reconnectionPromise != null) {
                                    log.info("Connection to {} restored.", future.channel().remoteAddress());
                                    ApnsClient.this.reconnectionPromise.trySuccess();
                                } else {
                                    log.info("Connected to {}.", future.channel().remoteAddress());
                                }

                                ApnsClient.this.reconnectDelaySeconds = INITIAL_RECONNECT_DELAY_SECONDS;
                                ApnsClient.this.reconnectionPromise = future.channel().newPromise();
                            }

                            ApnsClient.this.metricsListener.handleConnectionAttemptSucceeded(ApnsClient.this);
                        } else {
                            log.info("Failed to connect.", future.cause());

                            ApnsClient.this.metricsListener.handleConnectionAttemptFailed(ApnsClient.this);
                        }
                    }
                });
            }

            connectionReadyFuture = this.connectionReadyPromise;
        }
    }

    return connectionReadyFuture;
}

From source file:com.relayrides.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception {
    if (event instanceof IdleStateEvent) {
        assert PING_TIMEOUT < ApnsClient.PING_IDLE_TIME_MILLIS;

        log.trace("Sending ping due to inactivity.");

        final ByteBuf pingDataBuffer = context.alloc().ioBuffer(8, 8);
        pingDataBuffer.writeLong(this.nextPingId++);

        this.encoder().writePing(context, false, pingDataBuffer, context.newPromise())
                .addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override//w w  w  .  j  a  va  2s  .c o m
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            ApnsClientHandler.this.pingTimeoutFuture = future.channel().eventLoop()
                                    .schedule(new Runnable() {

                                        @Override
                                        public void run() {
                                            log.debug("Closing channel due to ping timeout.");
                                            future.channel().close();
                                        }
                                    }, PING_TIMEOUT, TimeUnit.SECONDS);
                        } else {
                            log.debug("Failed to write PING frame.", future.cause());
                            future.channel().close();
                        }
                    }
                });

        this.flush(context);
    }

    super.userEventTriggered(context, event);
}

From source file:com.relayrides.pushy.apns.ApnsConnection.java

License:Open Source License

/**
 * Asynchronously connects to the APNs gateway in this connection's environment. The outcome of the connection
 * attempt is reported via this connection's listener.
 *
 * @see ApnsConnectionListener#handleConnectionSuccess(ApnsConnection)
 * @see ApnsConnectionListener#handleConnectionFailure(ApnsConnection, Throwable)
 *///from   w w  w.  j  a v  a 2s. c o  m
@SuppressWarnings("deprecation")
public synchronized void connect() {

    final ApnsConnection<T> apnsConnection = this;

    if (this.connectFuture != null) {
        throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name));
    }

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // TODO Remove this when Netty 5 is available
    bootstrap.option(ChannelOption.AUTO_CLOSE, false);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = apnsConnection.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsConnectionHandler(apnsConnection));
        }
    });

    log.debug("{} beginning connection process.", apnsConnection.name);
    this.connectFuture = bootstrap.connect(this.environment.getApnsGatewayHost(),
            this.environment.getApnsGatewayPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(final ChannelFuture connectFuture) {
            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", apnsConnection.name);

                final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

                try {
                    sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

                        public void operationComplete(final Future<Channel> handshakeFuture) {
                            if (handshakeFuture.isSuccess()) {
                                log.debug("{} successfully completed TLS handshake.", apnsConnection.name);

                                apnsConnection.handshakeCompleted = true;
                                apnsConnection.listener.handleConnectionSuccess(apnsConnection);
                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs gateway.",
                                        apnsConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();
                                apnsConnection.listener.handleConnectionFailure(apnsConnection,
                                        handshakeFuture.cause());
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            apnsConnection.name);

                    connectFuture.channel().close();
                    apnsConnection.listener.handleConnectionFailure(apnsConnection, e);
                }
            } else {
                log.debug("{} failed to connect to APNs gateway.", apnsConnection.name, connectFuture.cause());

                apnsConnection.listener.handleConnectionFailure(apnsConnection, connectFuture.cause());
            }
        }
    });
}