Example usage for io.netty.channel ChannelFuture addListener

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

Introduction

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

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:io.netty.example.http.websocketx.server.WebSocketIndexPageHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    HttpResponseStatus responseStatus = res.status();
    if (responseStatus.code() != 200) {
        ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }/*www.  jav a 2 s  .co m*/
    // Send the response and close the connection if necessary.
    boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
    HttpUtil.setKeepAlive(res, keepAlive);
    ChannelFuture future = ctx.writeAndFlush(res);
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

public static Publisher<ClientTcpDuplexConnection> create(SocketAddress address,
        EventLoopGroup eventLoopGroup) {
    return s -> {
        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.AUTO_READ, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override/*from www  .ja v a 2 s.  c o m*/
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0,
                                BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0), clientHandler);
                    }
                }).connect(address);

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                Channel ch = connect.channel();
                s.onNext(new ClientTcpDuplexConnection(ch, subjects));
                s.onComplete();
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection.java

License:Apache License

@Override
public void addOutput(Publisher<Frame> o, Completable callback) {
    o.subscribe(new Subscriber<Frame>() {
        private Subscription subscription;

        @Override/*  w  w  w . j a va 2 s .com*/
        public void onSubscribe(Subscription s) {
            subscription = s;
            // TODO: wire back pressure
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Frame frame) {
            try {
                ByteBuf byteBuf = Unpooled.wrappedBuffer(frame.getByteBuffer());
                ChannelFuture channelFuture = channel.writeAndFlush(byteBuf);
                channelFuture.addListener(future -> {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        if (cause instanceof ClosedChannelException) {
                            onError(new TransportException(cause));
                        } else {
                            onError(cause);
                        }
                    }
                });
            } catch (Throwable t) {
                onError(t);
            }
        }

        @Override
        public void onError(Throwable t) {
            callback.error(t);
            subscription.cancel();
        }

        @Override
        public void onComplete() {
            callback.success();
            subscription.cancel();
        }
    });
}

From source file:io.reactivesocket.netty.tcp.server.ServerTcpDuplexConnection.java

License:Apache License

@Override
public void addOutput(Publisher<Frame> o, Completable callback) {
    o.subscribe(new Subscriber<Frame>() {
        @Override/* w  ww . j  a  v  a 2  s  .c om*/
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Frame frame) {
            try {
                ByteBuffer data = frame.getByteBuffer();
                ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
                ChannelFuture channelFuture = ctx.writeAndFlush(byteBuf);
                channelFuture.addListener(future -> {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        cause.printStackTrace();
                        callback.error(cause);
                    }
                });
            } catch (Throwable t) {
                onError(t);
            }
        }

        @Override
        public void onError(Throwable t) {
            callback.error(t);
        }

        @Override
        public void onComplete() {
            callback.success();
        }
    });
}

From source file:io.reactivesocket.netty.websocket.client.ClientWebSocketDuplexConnection.java

License:Apache License

public static Publisher<ClientWebSocketDuplexConnection> create(URI uri, EventLoopGroup eventLoopGroup) {
    return s -> {
        WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                WebSocketVersion.V13, null, false, new DefaultHttpHeaders());

        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//from  w w  w. j  a  va2s .c o m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                                new WebSocketClientProtocolHandler(handshaker), clientHandler);
                    }
                }).connect(uri.getHost(), uri.getPort());

        connect.addListener(connectFuture -> {
            if (connectFuture.isSuccess()) {
                final Channel ch = connect.channel();
                clientHandler.getHandshakePromise().addListener(handshakeFuture -> {
                    if (handshakeFuture.isSuccess()) {
                        s.onNext(new ClientWebSocketDuplexConnection(ch, subjects));
                        s.onComplete();
                    } else {
                        s.onError(handshakeFuture.cause());
                    }
                });
            } else {
                s.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.reactivesocket.netty.websocket.client.ClientWebSocketDuplexConnection.java

License:Apache License

@Override
public void addOutput(Publisher<Frame> o, Completable callback) {
    o.subscribe(new Subscriber<Frame>() {
        private Subscription subscription;

        @Override//w ww.j a  va  2 s .c om
        public void onSubscribe(Subscription s) {
            subscription = s;
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Frame frame) {
            try {
                ByteBuf byteBuf = Unpooled.wrappedBuffer(frame.getByteBuffer());
                BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(byteBuf);
                ChannelFuture channelFuture = channel.writeAndFlush(binaryWebSocketFrame);
                channelFuture.addListener(future -> {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        if (cause instanceof ClosedChannelException) {
                            onError(new TransportException(cause));
                        } else {
                            onError(cause);
                        }
                    }
                });
            } catch (Throwable t) {
                onError(t);
            }
        }

        @Override
        public void onError(Throwable t) {
            callback.error(t);
            if (t instanceof TransportException) {
                subscription.cancel();
            }
        }

        @Override
        public void onComplete() {
            callback.success();
        }
    });
}

From source file:io.reactivesocket.netty.websocket.server.ServerWebSocketDuplexConnection.java

License:Apache License

@Override
public void addOutput(Publisher<Frame> o, Completable callback) {
    o.subscribe(new Subscriber<Frame>() {
        @Override//from   w  w w.  j av a2 s  . co  m
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Frame frame) {
            try {
                ByteBuffer data = frame.getByteBuffer();
                ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
                BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(byteBuf);
                ChannelFuture channelFuture = ctx.writeAndFlush(binaryWebSocketFrame);
                channelFuture.addListener(future -> {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        cause.printStackTrace();
                        callback.error(cause);
                    }
                });
            } catch (Throwable t) {
                onError(t);
            }
        }

        @Override
        public void onError(Throwable t) {
            callback.error(t);
        }

        @Override
        public void onComplete() {
            callback.success();
        }
    });
}

From source file:io.reactivesocket.transport.websocket.client.ClientWebSocketDuplexConnection.java

License:Apache License

public static Publisher<ClientWebSocketDuplexConnection> create(URI uri, EventLoopGroup eventLoopGroup) {
    return subscriber -> {
        WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                WebSocketVersion.V13, null, false, new DefaultHttpHeaders());

        CopyOnWriteArrayList<Observer<Frame>> subjects = new CopyOnWriteArrayList<>();
        ReactiveSocketClientHandler clientHandler = new ReactiveSocketClientHandler(subjects);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//  ww  w.ja  v a  2s.c  o m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                                new WebSocketClientProtocolHandler(handshaker), clientHandler);
                    }
                }).connect(uri.getHost(), uri.getPort());

        connect.addListener(connectFuture -> {
            subscriber.onSubscribe(EmptySubscription.INSTANCE);
            if (connectFuture.isSuccess()) {
                final Channel ch = connect.channel();
                clientHandler.getHandshakePromise().addListener(handshakeFuture -> {
                    if (handshakeFuture.isSuccess()) {
                        subscriber.onNext(new ClientWebSocketDuplexConnection(ch, subjects));
                        subscriber.onComplete();
                    } else {
                        subscriber.onError(handshakeFuture.cause());
                    }
                });
            } else {
                subscriber.onError(connectFuture.cause());
            }
        });
    };
}

From source file:io.reactivex.netty.channel.ObservableConnection.java

License:Apache License

@SuppressWarnings("unchecked")
protected Observable<Void> _closeChannel() {
    closeStartTimeMillis = Clock.newStartTimeMillis();
    eventsSubject.onEvent(metricEventProvider.getChannelCloseStartEvent());

    final ChannelFuture closeFuture = getChannelHandlerContext().close();

    /**/*from www  .ja  v a  2 s . c  o  m*/
     * This listener if added inside the returned Observable onSubscribe() function, would mean that the
     * metric events will only be fired if someone subscribed to the close() Observable. However, we need them to
     * fire independent of someone subscribing.
     */
    closeFuture.addListener(new ChannelFutureListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                eventsSubject.onEvent(metricEventProvider.getChannelCloseSuccessEvent(),
                        Clock.onEndMillis(closeStartTimeMillis));
            } else {
                eventsSubject.onEvent(metricEventProvider.getChannelCloseFailedEvent(),
                        Clock.onEndMillis(closeStartTimeMillis), future.cause());
            }
        }
    });

    return Observable.create(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            closeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        subscriber.onCompleted();
                    } else {
                        subscriber.onError(future.cause());
                    }
                }
            });
        }
    });
}

From source file:io.reactivex.netty.client.ClientChannelFactoryImpl.java

License:Apache License

@Override
public ChannelFuture connect(final Subscriber<? super ObservableConnection<I, O>> subscriber,
        RxClient.ServerInfo serverInfo,/*  w w w .  j a v  a  2  s  .c o m*/
        final ClientConnectionFactory<I, O, ? extends ObservableConnection<I, O>> connectionFactory) {
    final long startTimeMillis = Clock.newStartTimeMillis();
    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_START);
    final ChannelFuture connectFuture = clientBootstrap.connect(serverInfo.getHost(), serverInfo.getPort());

    subscriber.add(Subscriptions.create(new Action0() {
        @Override
        public void call() {
            if (!connectFuture.isDone()) {
                connectFuture.cancel(true); // Unsubscribe here means, no more connection is required. A close on connection is explicit.
            }
        }
    }));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (!future.isSuccess()) {
                    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_FAILED, Clock.onEndMillis(startTimeMillis),
                            future.cause());
                    subscriber.onError(future.cause());
                } else {
                    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_SUCCESS,
                            Clock.onEndMillis(startTimeMillis));
                    ChannelPipeline pipeline = future.channel().pipeline();
                    ChannelHandlerContext ctx = pipeline.lastContext(); // The connection uses the context for write which should always start from the tail.
                    final ObservableConnection<I, O> newConnection = connectionFactory.newConnection(ctx);
                    ChannelHandler lifecycleHandler = pipeline
                            .get(RxRequiredConfigurator.CONN_LIFECYCLE_HANDLER_NAME);
                    if (null == lifecycleHandler) {
                        onNewConnection(newConnection, subscriber);
                    } else {
                        @SuppressWarnings("unchecked")
                        ConnectionLifecycleHandler<I, O> handler = (ConnectionLifecycleHandler<I, O>) lifecycleHandler;
                        SslHandler sslHandler = pipeline.get(SslHandler.class);
                        if (null == sslHandler) {
                            handler.setConnection(newConnection);
                            onNewConnection(newConnection, subscriber);
                        } else {
                            sslHandler.handshakeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Channel>>() {
                                        @Override
                                        public void operationComplete(Future<? super Channel> future)
                                                throws Exception {
                                            onNewConnection(newConnection, subscriber);
                                        }
                                    });
                        }
                    }
                }
            } catch (Throwable throwable) {
                subscriber.onError(throwable);
            }
        }
    });
    return connectFuture;
}