Search in sources :

Example 96 with Channel

use of io.netty.channel.Channel in project pravega by pravega.

the class ClientConnectionInboundHandler method channelRegistered.

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    super.channelRegistered(ctx);
    Channel c = ctx.channel();
    channel.set(c);
    // release all futures waiting for channel registration to complete.
    registeredFutureLatch.release(null);
    log.info("Connection established {} ", ctx);
    c.write(new WireCommands.Hello(WireCommands.WIRE_VERSION, WireCommands.OLDEST_COMPATIBLE_VERSION), c.voidPromise());
    ScheduledFuture<?> old = keepAliveFuture.getAndSet(c.eventLoop().scheduleWithFixedDelay(new KeepAliveTask(), 20, 10, TimeUnit.SECONDS));
    if (old != null) {
        old.cancel(false);
    }
}
Also used : Channel(io.netty.channel.Channel) WireCommands(io.pravega.shared.protocol.netty.WireCommands)

Example 97 with Channel

use of io.netty.channel.Channel in project pravega by pravega.

the class ConnectionFactoryImpl method establishConnection.

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (clientConfig.isEnableTls()) {
        try {
            SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
            if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
            } else {
                sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
            }
            sslCtx = sslCtxFactory.build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
                if (clientConfig.isValidateHostName()) {
                    SSLEngine sslEngine = sslHandler.engine();
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    sslEngine.setSSLParameters(sslParameters);
                }
                p.addLast(sslHandler);
            }
            // p.addLast(new LoggingHandler(LogLevel.INFO));
            p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
        }
    });
    // Start the client.
    CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // since ChannelFuture is complete future.channel() is not a blocking call.
                    Channel ch = future.channel();
                    log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
                    // Once a channel is closed the channel group implementation removes it.
                    allChannels.add(ch);
                    connectionComplete.complete(handler);
                } else {
                    connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
                }
            }
        });
    } catch (Exception e) {
        connectionComplete.completeExceptionally(new ConnectionFailedException(e));
    }
    // check if channel is registered.
    CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
    handler.completeWhenRegistered(channelRegisteredFuture);
    return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CommandEncoder(io.pravega.shared.protocol.netty.CommandEncoder) SSLException(javax.net.ssl.SSLException) CompletableFuture(java.util.concurrent.CompletableFuture) SSLParameters(javax.net.ssl.SSLParameters) ExceptionLoggingHandler(io.pravega.shared.protocol.netty.ExceptionLoggingHandler) Bootstrap(io.netty.bootstrap.Bootstrap) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) CommandDecoder(io.pravega.shared.protocol.netty.CommandDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) File(java.io.File) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 98 with Channel

use of io.netty.channel.Channel in project baseio by generallycloud.

the class NettyClientThread method main.

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new HelloClient());
            }
        });
        System.out.println("################## Test start ####################");
        ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
        System.out.println(f.isSuccess());
        Channel channel = f.channel();
        System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
        int len = 1024 * 64;
        StringBuilder s = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            s.append(len % 10);
        }
        final String msg = s.toString();
        ThreadUtil.execute(new Runnable() {

            @Override
            public void run() {
                int i = 0;
                for (; ; ) {
                    // String s = "hello Service! ---> :" + i;
                    ChannelFuture f = channel.writeAndFlush(msg);
                    ThreadUtil.sleep(1);
                    System.out.println(f.isDone() + "--------" + i);
                    i++;
                }
            }
        });
        ThreadUtil.sleep(Integer.MAX_VALUE);
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 99 with Channel

use of io.netty.channel.Channel in project reactor-netty by reactor.

the class ReactorNetty method addHandlerBeforeReactorEndHandlers.

/**
 * A common implementation for the {@link NettyContext#addHandlerLast(String, ChannelHandler)}
 * method that can be reused by other implementors.
 * <p>
 * This implementation will look for reactor added handlers on the right hand side of
 * the pipeline, provided they are identified with the {@link NettyPipeline#RIGHT}
 * prefix, and add the handler just before the first of these.
 *
 * @param context the {@link NettyContext} on which to add the decoder.
 * @param name the name of the decoder.
 * @param handler the decoder to add before the final reactor-specific handlers.
 * @see NettyContext#addHandlerLast(String, ChannelHandler).
 */
static void addHandlerBeforeReactorEndHandlers(NettyContext context, String name, ChannelHandler handler) {
    Objects.requireNonNull(name, "name");
    Objects.requireNonNull(handler, "handler");
    Channel channel = context.channel();
    boolean exists = channel.pipeline().get(name) != null;
    if (exists) {
        if (log.isDebugEnabled()) {
            log.debug("Handler [{}] already exists in the pipeline, decoder has been skipped", name);
        }
        return;
    }
    // we need to find the correct position
    String before = null;
    for (String s : channel.pipeline().names()) {
        if (s.startsWith(NettyPipeline.RIGHT)) {
            before = s;
            break;
        }
    }
    if (before == null) {
        channel.pipeline().addLast(name, handler);
    } else {
        channel.pipeline().addBefore(NettyPipeline.ReactiveBridge, name, handler);
    }
    registerForClose(shouldCleanupOnClose(channel), name, context);
    if (log.isDebugEnabled()) {
        log.debug("Added decoder [{}] at the end of the user pipeline, full pipeline: {}", name, channel.pipeline().names());
    }
}
Also used : Channel(io.netty.channel.Channel)

Example 100 with Channel

use of io.netty.channel.Channel in project atomix by atomix.

the class NettyMessagingService method openChannel.

private CompletableFuture<Channel> openChannel(Endpoint ep) {
    Bootstrap bootstrap = bootstrapClient(ep);
    CompletableFuture<Channel> retFuture = new CompletableFuture<>();
    ChannelFuture f = bootstrap.connect();
    f.addListener(future -> {
        if (future.isSuccess()) {
            retFuture.complete(f.channel());
        } else {
            retFuture.completeExceptionally(future.cause());
        }
    });
    log.debug("Established a new connection to {}", ep);
    return retFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) CompletableFuture(java.util.concurrent.CompletableFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Aggregations

Channel (io.netty.channel.Channel)884 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)226 ChannelFuture (io.netty.channel.ChannelFuture)204 Test (org.junit.Test)203 Bootstrap (io.netty.bootstrap.Bootstrap)199 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)191 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)177 InetSocketAddress (java.net.InetSocketAddress)165 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)132 IOException (java.io.IOException)126 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)106 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)96 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)89