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.xx_dev.apn.socks.remote.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from w ww  . j ava  2s . c om
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .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 {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                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 DirectClientHandler(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.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.yahoo.pulsar.common.api.PulsarHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.remoteAddress = ctx.channel().remoteAddress();
    this.ctx = ctx;

    if (log.isDebugEnabled()) {
        log.debug("[{}] Scheduling keep-alive task every {} s", ctx.channel(), keepAliveIntervalSeconds);
    }//from ww  w  . ja  v  a2  s.c  om
    if (keepAliveIntervalSeconds > 0) {
        this.keepAliveTask = ctx.executor().scheduleAtFixedRate(this::handleKeepAliveTimeout,
                keepAliveIntervalSeconds, keepAliveIntervalSeconds, TimeUnit.SECONDS);
    }
}

From source file:com.zaradai.distributor.messaging.netty.handler.AbstractHandshakeHandler.java

License:Apache License

private Future<Channel> handshake(final ChannelHandlerContext handlerContext) {
    handshakePromise = new DefaultPromise<Channel>(handlerContext.executor());
    final ScheduledFuture<?> timeoutFuture;
    if (handshakeTimeout > 0) {
        timeoutFuture = handlerContext.executor().schedule(new Runnable() {
            @Override/*from   w w w. j a va 2  s.  co  m*/
            public void run() {
                if (handshakePromise.isDone()) {
                    return;
                }
                notifyHandshakeFailure(handlerContext, HANDSHAKE_TIMED_OUT);
            }
        }, handshakeTimeout, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    handshakePromise.addListener(new GenericFutureListener<Future<? super Channel>>() {
        @Override
        public void operationComplete(Future<? super Channel> future) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
        }
    });

    try {
        beginHandshake(handlerContext);
    } catch (Exception e) {
        notifyHandshakeFailure(handlerContext, e);
    }

    return handshakePromise;
}

From source file:com.zhaopeng.timeserver.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????//from w ww .j  a  va2  s . co m
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new 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.zz.learning.netty5.chap12.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????//  w w w  .  j  a  v a 2  s. 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:cyril.server.io.AuthHandler.java

License:Open Source License

@Override
protected void initialize(ChannelHandlerContext ctx) {
    wrapped = auth.wrap(ctx.channel());//from  www . j a v a  2  s.  c o m
    killTask = ctx.executor().schedule(new KillTask(ctx), ProtocolConstants.AUTH_TIMEOUT, TimeUnit.SECONDS);
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

public ChannelFuture close(final ChannelPromise future) {
    final ChannelHandlerContext ctx = this.ctx;
    ctx.executor().execute(new Runnable() {
        @Override//from w  w w  .  ja  v  a 2  s  .  c  o  m
        public void run() {
            engine.closeOutbound();
            try {
                write(ctx, Unpooled.EMPTY_BUFFER, future);
                flush(ctx);
            } catch (Exception e) {
                if (!future.tryFailure(e)) {
                    logger.warn("flush() raised a masked exception.", e);
                }
            }
        }
    });

    return future;
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private void safeClose(final ChannelHandlerContext ctx, ChannelFuture flushFuture,
        final ChannelPromise promise) {
    if (!ctx.channel().isActive()) {
        ctx.close(promise);/*from www . j av  a  2 s .c o  m*/
        return;
    }

    final ScheduledFuture<?> timeoutFuture;
    if (closeNotifyTimeoutMillis > 0) {
        // Force-close the connection if close_notify is not fully sent in time.
        timeoutFuture = ctx.executor().schedule(new Runnable() {
            @Override
            public void run() {
                logger.warn(
                        ctx.channel() + " last write attempt timed out." + " Force-closing the connection.");
                ctx.close(promise);
            }
        }, closeNotifyTimeoutMillis, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    // Close the connection if close_notify is sent in time.
    flushFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
            // Trigger the close in all cases to make sure the promise is notified
            // See https://github.com/netty/netty/issues/2358
            ctx.close(promise);
        }
    });
}

From source file:http2.bench.netty.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//from   w  ww  . j  a  v a2 s .  c o  m
    ctx.executor().schedule(() -> {
        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        if (!keepAlive) {
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            ctx.writeAndFlush(response);
        }
    }, 20, TimeUnit.MILLISECONDS);
}

From source file:io.airlift.drift.transport.netty.client.ThriftClientHandler.java

License:Apache License

private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise)
        throws Exception {
    // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed
    int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet();
    RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId);

    // register timeout
    requestHandler.registerRequestTimeout(context.executor());

    // write request
    ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc());

    // register request if we are expecting a response
    if (!thriftRequest.isOneway()) {
        if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) {
            requestHandler.onChannelError(
                    new TTransportException("Another request with the same sequenceId is already in progress"));
            requestBuffer.release();//from  w ww.j  a v a  2s .  com
            return;
        }
    }

    // if this connection is failed, immediately fail the request
    TException channelError = this.channelError.get();
    if (channelError != null) {
        thriftRequest.failed(channelError);
        requestBuffer.release();
        return;
    }

    try {
        ThriftFrame thriftFrame = new ThriftFrame(sequenceId, requestBuffer, thriftRequest.getHeaders(),
                transport, protocol, true);

        ChannelFuture sendFuture = context.write(thriftFrame, promise);
        sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler));
    } catch (Throwable t) {
        onError(context, t, Optional.of(requestHandler));
        requestBuffer.release();
    }
}