Example usage for io.netty.channel ChannelHandlerContext executor

List of usage examples for io.netty.channel ChannelHandlerContext executor

Introduction

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

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:com.github.netfreer.shadowducks.client.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from  www  .  j a va2  s . co  m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME);
                final long parseTime = beginTimeAttr.get();
                long usedTime = System.currentTimeMillis() - parseTime;
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                    logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                }
                beginTimeAttr.set(null);
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

/**
 * Create new promised callback on outbound channel operation complete.
 * //  w  w w.ja  v  a  2s  . co  m
 * @param ctx
 * @param request
 * @return Promise
 */
protected Promise<Channel> newOutboundPromise(final ChannelHandlerContext ctx, final SocksCmdRequest request) {
    final Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(ConnectBackendHandler.this);
                                outboundChannel.pipeline().addLast(new RelayTrafficHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayTrafficHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                NettyChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    return promise;
}

From source file:com.github.wangshuwei5.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = JSON.parseObject((String) msg, NettyMessage.class);
    // ?????//from  w  w w .  j a  va  2s.  c  om
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.gxkj.demo.netty.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/* ww  w .  jav a 2s  .c  o  m*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                ctx.pipeline().remove(getName());
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.channel().pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientInitializer(promise));

    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.heelenyc.im.client.handler.ClientHeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Message message = (Message) msg;/*from   ww w.  ja v  a  2s .  c  om*/
    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new ClientHeartBeatReqHandler.HeartBeatTask(ctx), 0,
                Constans.HEARTBEAT_PERIOD_INMS, TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        logger.info("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.heliosapm.streams.forwarder.HttpJsonOutboundHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from  w w w. j  a  v a2  s  .c om*/
 * @see io.netty.handler.codec.MessageToMessageEncoder#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)
 */
@Override
protected void encode(final ChannelHandlerContext ctx, final ConsumerRecords<String, StreamedMetricValue> msg,
        final List<Object> out) throws Exception {
    final StreamedMetricValue[] smvs = StreamSupport.stream(msg.spliterator(), true)
            .map(new Function<ConsumerRecord<String, StreamedMetricValue>, StreamedMetricValue>() {
                @Override
                public StreamedMetricValue apply(ConsumerRecord<String, StreamedMetricValue> t) {
                    return t.value();
                }

            }).toArray(s -> new StreamedMetricValue[s]);
    final int size = smvs.length;
    final ByteBuf buff = buffManager.buffer(size * 200);

    JSONOps.serializeAndGzip(smvs, buff);
    final int sz = buff.readableBytes();
    final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, postUri,
            buff);
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    request.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
    request.headers().set(HttpHeaderNames.CONTENT_LENGTH, buff.readableBytes());
    out.add(request);

    ctx.executor().execute(new Runnable() {
        public void run() {
            final NonBlockingHashSet<String> hosts = new NonBlockingHashSet<String>();
            StreamSupport.stream(msg.spliterator(), true)
                    .map(new Function<ConsumerRecord<String, StreamedMetricValue>, String>() {
                        @Override
                        public String apply(ConsumerRecord<String, StreamedMetricValue> t) {
                            return t.value().getTags().get("host");
                        }
                    }).forEach(h -> hosts.add(h));
            log.info("Hosts:{}, Size: {}", hosts, sz);
        }
    });
}

From source file:com.hop.hhxx.example.http2.tiles.Http1RequestHandler.java

License:Apache License

@Override
protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
        final FullHttpResponse response, final FullHttpRequest request) {
    HttpUtil.setContentLength(response, response.content().readableBytes());
    ctx.executor().schedule(new Runnable() {
        @Override//w ww.  ja  v a  2s .c  o  m
        public void run() {
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.writeAndFlush(response);
            } else {
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }, latency, TimeUnit.MILLISECONDS);
}

From source file:com.hop.hhxx.example.http2.tiles.Http2RequestHandler.java

License:Apache License

protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
        final FullHttpResponse response, final FullHttpRequest request) {
    setContentLength(response, response.content().readableBytes());
    streamId(response, streamId);//w w  w  .j  av  a2s.co  m
    ctx.executor().schedule(new Runnable() {
        @Override
        public void run() {
            ctx.writeAndFlush(response);
        }
    }, latency, TimeUnit.MILLISECONDS);
}

From source file:com.hop.hhxx.example.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override// w  ww  . j  a  v a2  s  . co m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(ctx.channel()));
                            ctx.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new io.netty.example.socksproxy.DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(ctx.channel()));
                            ctx.pipeline()
                                    .addLast(new io.netty.example.socksproxy.RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    io.netty.example.socksproxy.SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.jjzhk.Chapter14.netty.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else/*from w  w  w .  j  a  v  a  2s .  c o  m*/
        ctx.fireChannelRead(msg);
}