Example usage for io.netty.channel Channel eventLoop

List of usage examples for io.netty.channel Channel eventLoop

Introduction

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

Prototype

EventLoop eventLoop();

Source Link

Document

Return the EventLoop this Channel was registered to.

Usage

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx/*  w  w  w  . j  a v  a2  s .c  om*/
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:alluxio.client.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context//from   w ww.  ja v a2 s.c  om
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request));
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        throw new IOException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponse(message.asResponse());
    }
    return message;
}

From source file:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context//from w w w .j  a v  a  2s  .  c  o m
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    final Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
            promise.tryFailure(future.cause());
        }
    });
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        CommonUtils.closeChannel(channel);
        throw new IOException(e);
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponseFrom(message.asResponse(), context.getChannel());
    }
    return message;
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

private void closeChannelAndEventLoop(Channel c) {
    c.flush();
    c.deregister();
    c.close();
    c.eventLoop().shutdownGracefully();
}

From source file:cn.david.socks.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  a  v  a  2 s.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) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.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 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.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.caricah.iotracah.server.netty.ServerImpl.java

License:Apache License

public void pushToClient(String connectionId, T message) {

    log.debug(" pushToClient : Server pushToClient : we got to now sending out {}", message);

    Channel channel = getChannel(connectionId);

    if (null != channel) {

        channel.eventLoop().execute(() -> channel.writeAndFlush(message, channel.voidPromise()));

    } else {//w  w  w  . j a va 2  s .c  om
        log.info(" pushToClient : channel to push message {} is not available ", message);
    }
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {//from   w w  w.  j  a v  a 2s  . c  o m

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.comphenix.protocol.compat.netty.independent.NettyBootstrapList.java

License:Open Source License

/**
 * Revert any changes we made to the channel future.
 * @param future - the future.//from  w  w w  .j av a2 s.  c  om
 */
protected void unprocessBootstrap(ChannelFuture future) {
    final Channel channel = future.channel();

    // For thread safety - see ChannelInjector.close()
    channel.eventLoop().submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            channel.pipeline().remove(handler);
            return null;
        }
    });
}

From source file:com.comphenix.protocol.injector.netty.ProtocolInjector.java

License:Open Source License

/**
 * Inject into the spigot connection class.
 *//* w  ww  .j a  va  2 s.co  m*/
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        List<Method> serverConnectionMethods = fuzzyServer
                .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {});

        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = null;

        for (Method method : serverConnectionMethods) {
            try {
                serverConnection = method.invoke(server);

                // Continue until we get a server connection
                if (serverConnection != null) {
                    break;
                }
            } catch (Exception e) {
                // Try the next though
                e.printStackTrace();
            }
        }

        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(final Channel channel) throws Exception {
                try {
                    synchronized (networkManagers) {
                        // For some reason it needs to be delayed on 1.12, but the delay breaks 1.11 and below
                        // TODO I see this more as a temporary hotfix than a permanent solution
                        if (MinecraftVersion.getCurrentVersion().getMinor() >= 12) {
                            channel.eventLoop().submit(() -> injectionFactory
                                    .fromChannel(channel, ProtocolInjector.this, playerFactory).inject());
                        } else {
                            injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory)
                                    .inject();
                        }
                    }
                } catch (Exception e) {
                    reporter.reportDetailed(ProtocolInjector.this, Report
                            .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e));
                }
            }
        };

        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };

        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;

                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };

        FuzzyReflection fuzzy = FuzzyReflection.fromObject(serverConnection, true);

        try {
            List<Field> fields = fuzzy.getFieldListByType(List.class);
            for (Field field : fields) {
                ParameterizedType param = (ParameterizedType) field.getGenericType();
                if (param.getActualTypeArguments()[0].equals(MinecraftReflection.getNetworkManagerClass())) {
                    field.setAccessible(true);
                    networkManagers = (List<Object>) field.get(serverConnection);
                }
            }
        } catch (Exception ex) {
            networkManagers = (List<Object>) fuzzy
                    .getMethodByParameters("getNetworkManagers", List.class, serverConnection.getClass())
                    .invoke(null, serverConnection);
        }

        if (networkManagers == null) {
            throw new RuntimeException("Failed to obtain list of network managers.");
        }

        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);

        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();

            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }

            // Synchronize with each list before we attempt to replace them.
            field.setValue(new BootstrapList(list, connectionHandler));
        }

        injected = true;
    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

public UaTcpClientMessageHandler(UaTcpStackClient client, ClientSecureChannel secureChannel,
        SerializationQueue serializationQueue, CompletableFuture<ClientSecureChannel> handshakeFuture) {

    this.client = client;
    this.secureChannel = secureChannel;
    this.serializationQueue = serializationQueue;
    this.handshakeFuture = handshakeFuture;

    secureChannel.attr(KEY_PENDING_REQUEST_FUTURES).setIfAbsent(Maps.newConcurrentMap());

    pending = secureChannel.attr(KEY_PENDING_REQUEST_FUTURES).get();

    secureChannel.attr(ClientSecureChannel.KEY_REQUEST_ID_SEQUENCE)
            .setIfAbsent(new LongSequence(1L, UInteger.MAX_VALUE));

    requestIdSequence = secureChannel.attr(ClientSecureChannel.KEY_REQUEST_ID_SEQUENCE).get();

    handshakeFuture.thenAccept(sc -> {
        Channel channel = sc.getChannel();

        channel.eventLoop().execute(() -> {
            List<UaRequestFuture> awaitingHandshake = channel
                    .attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE).get();

            if (awaitingHandshake != null) {
                channel.attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE).remove();

                logger.debug("{} message(s) queued before handshake completed; sending now.",
                        awaitingHandshake.size());
                awaitingHandshake.forEach(channel::writeAndFlush);
            }//from w  w w  . j  a  v  a  2  s. c om
        });
    });
}