Search in sources :

Example 46 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project baseio by generallycloud.

the class TestLoadEchoClient1 method prepare.

@Override
public void prepare() throws Exception {
    eventHandleAdaptor = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // System.out.println("_________________"+msg);
            // ctx.write(msg);
            addCount(1);
        }
    };
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, false);
    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", eventHandleAdaptor);
        }
    });
    f = b.connect("localhost", 5656).sync();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 47 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project carbondata by apache.

the class NonSecureDictionaryClient method startClient.

/**
 * start dictionary client
 *
 * @param address
 * @param port
 */
@Override
public void startClient(String secretKey, String address, int port, boolean encryptSecureServer) {
    LOGGER.audit("Starting client on " + address + " " + port);
    long start = System.currentTimeMillis();
    // Create an Event with 1 thread.
    workerGroup = new NioEventLoopGroup(1);
    Bootstrap clientBootstrap = new Bootstrap();
    clientBootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            // Based on length provided at header, it collects all packets
            pipeline.addLast("LengthDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 2, 0, 2));
            pipeline.addLast("NonSecureDictionaryClientHandler", nonSecureDictionaryClientHandler);
        }
    });
    clientBootstrap.connect(new InetSocketAddress(address, port));
    LOGGER.info("Dictionary client Started, Total time spent : " + (System.currentTimeMillis() - start));
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 48 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project java-tron by tronprotocol.

the class UDPListener method start.

public void start() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        discoveryExecutor = new DiscoveryExecutor(nodeManager);
        discoveryExecutor.start();
        while (!shutdown) {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<NioDatagramChannel>() {

                @Override
                public void initChannel(NioDatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(stats.udp);
                    ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                    ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast(new PacketDecoder());
                    MessageHandler messageHandler = new MessageHandler(ch, nodeManager);
                    nodeManager.setMessageSender(messageHandler);
                    ch.pipeline().addLast(messageHandler);
                }
            });
            channel = b.bind(port).sync().channel();
            logger.info("Discovery UDPListener started, bind port {}", port);
            channel.closeFuture().sync();
            if (shutdown) {
                logger.info("Shutdown discovery UDPListener");
                break;
            }
            logger.warn("UDP channel closed. Recreating after 5 sec pause...");
            Thread.sleep(5000);
        }
    } catch (Exception e) {
        if (e instanceof BindException && e.getMessage().contains("Address already in use")) {
            logger.error("Port " + port + " is busy. Check if another instance is running with the same port.");
        } else {
            logger.error("Can't start discover: ", e);
        }
    } finally {
        group.shutdownGracefully().sync();
    }
}
Also used : NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ProtobufVarint32LengthFieldPrepender(io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender) Bootstrap(io.netty.bootstrap.Bootstrap) BindException(java.net.BindException) ProtobufVarint32FrameDecoder(io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) BindException(java.net.BindException)

Example 49 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap 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)

Example 50 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project herddb by diennea.

the class NettyConnector method connect.

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup) throws IOException {
    try {
        final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        Class<? extends Channel> channelType;
        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);
        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();
        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).handler(new ChannelInitializer<Channel>() {

            @Override
            public void initChannel(Channel ch) throws Exception {
                NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                result.set(channel);
                channel.setMessagesReceiver(receiver);
                if (ssl) {
                    ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                if (socketTimeout > 0) {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                }
                ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                // 
                ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                ch.pipeline().addLast(new InboundMessageHandler(channel));
            }
        });
        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        return result.get();
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) MultithreadEventLoopGroup(io.netty.channel.MultithreadEventLoopGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)429 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)207 Channel (io.netty.channel.Channel)194 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)189 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)169 ChannelFuture (io.netty.channel.ChannelFuture)152 EventLoopGroup (io.netty.channel.EventLoopGroup)139 SocketChannel (io.netty.channel.socket.SocketChannel)123 InetSocketAddress (java.net.InetSocketAddress)119 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)113 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)108 Test (org.junit.jupiter.api.Test)89 ChannelPipeline (io.netty.channel.ChannelPipeline)76 LocalChannel (io.netty.channel.local.LocalChannel)74 LocalServerChannel (io.netty.channel.local.LocalServerChannel)71 LocalAddress (io.netty.channel.local.LocalAddress)66 CountDownLatch (java.util.concurrent.CountDownLatch)62 IOException (java.io.IOException)60 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)56 ChannelInitializer (io.netty.channel.ChannelInitializer)45