Search in sources :

Example 51 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class NettyRemotingClient method start.

@Override
public void start() {
    this.defaultEventExecutorGroup = new // 
    DefaultEventExecutorGroup(// 
    nettyClientConfig.getClientWorkerThreads(), new ThreadFactory() {

        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
        }
    });
    // netty客户端
    Bootstrap handler = // 
    this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis()).option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize()).option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize()).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(defaultEventExecutorGroup, // 编码
            new NettyEncoder(), // 解码
            new NettyDecoder(), // 心跳检查
            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyClientHandler());
        }
    });
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingClient.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RemotingTooMuchRequestException(org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException) RemotingConnectException(org.apache.rocketmq.remoting.exception.RemotingConnectException) RemotingSendRequestException(org.apache.rocketmq.remoting.exception.RemotingSendRequestException) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException) TimerTask(java.util.TimerTask) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 52 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project ballerina by ballerina-lang.

the class WebSocketClient method handhshake.

/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone = false;
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    group = new NioEventLoopGroup();
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    headers.entrySet().forEach(header -> {
        httpHeaders.add(header.getKey(), header.getValue());
    });
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders));
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });
        channel = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
    } catch (Exception e) {
        logger.error("Handshake unsuccessful : " + e.getMessage(), e);
        return false;
    }
    logger.info("WebSocket Handshake successful : " + isDone);
    return isDone;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 53 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project ballerina by ballerina-lang.

the class WebSocketClient method handshake.

/**
 * @param callback callback which should be called when a response is received.
 * @return true if the handshake is done properly.
 * @throws URISyntaxException   throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handshake(Callback callback) throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone;
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        LOGGER.debug("Only WS(S) is supported.");
        return false;
    }
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    headers.forEach(httpHeaders::add);
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders), callback);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });
        channel = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
    } catch (Exception e) {
        LOGGER.debug("Handshake unsuccessful : " + e.getMessage(), e);
        group.shutdownGracefully();
        return false;
    }
    LOGGER.debug("WebSocket Handshake successful: {}", isDone);
    return isDone;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) URISyntaxException(java.net.URISyntaxException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Bootstrap(io.netty.bootstrap.Bootstrap) SslContext(io.netty.handler.ssl.SslContext)

Example 54 with Bootstrap

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

the class DefaultClientPool method init.

private void init(String url, int maxCount) throws URISyntaxException, SSLException {
    URI uri = new URI(url);
    if (uri.getScheme() == null || uri.getHost() == null) {
        throw new IllegalArgumentException("uri不合法");
    }
    scheme = uri.getScheme();
    host = uri.getHost();
    port = uri.getPort();
    if (port == -1) {
        if (HttpScheme.HTTP.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    if (!HttpScheme.HTTP.equalsIgnoreCase(scheme) && !HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
        if (log.isErrorEnabled()) {
            log.error("仅有HTTP(S)是支持的。");
        }
        return;
    }
    final boolean ssl = HttpScheme.HTTPS.equalsIgnoreCase(scheme);
    this.setSSlContext(ssl);
    final Bootstrap b = new Bootstrap();
    b.group(GROUP).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true).remoteAddress(InetSocketAddress.createUnresolved(host, port));
    channelPool = new FixedChannelPool(b, new HttpClientChannelPoolHandler(sslContext), maxCount);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) FixedChannelPool(io.netty.channel.pool.FixedChannelPool) Bootstrap(io.netty.bootstrap.Bootstrap) HttpClientChannelPoolHandler(pro.tools.http.netty.handler.HttpClientChannelPoolHandler) URI(java.net.URI)

Example 55 with Bootstrap

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

the class PerChannelBookieClient method connect.

protected ChannelFuture connect() {
    final long startTime = MathUtils.nowInNano();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to bookie: {}", addr);
    }
    // Set up the ClientBootStrap so we can create a new Channel connection to the bookie.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bootstrap.channel(LocalChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }
    ByteBufAllocator allocator;
    if (this.conf.isNettyUsePooledBuffers()) {
        allocator = PooledByteBufAllocator.DEFAULT;
    } else {
        allocator = UnpooledByteBufAllocator.DEFAULT;
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis());
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark()));
    if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) {
        bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay());
        bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive());
        // if buffer sizes are 0, let OS auto-tune it
        if (conf.getClientSendBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize());
        }
        if (conf.getClientReceiveBufferSize() > 0) {
            bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize());
        }
    }
    // In the netty pipeline, we need to split packets based on length, so we
    // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions
    // are carried out in this class, e.g., making sense of received messages,
    // prepending the length to outgoing packets etc.
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);
            pipeline.addLast("lengthbasedframedecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
            pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
            pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry));
            pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol));
            pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory, txnIdGenerator, connectionPeer));
            pipeline.addLast("mainhandler", PerChannelBookieClient.this);
        }
    });
    SocketAddress bookieAddr = addr.getSocketAddress();
    if (eventLoopGroup instanceof DefaultEventLoopGroup) {
        bookieAddr = addr.getLocalAddress();
    }
    ChannelFuture future = bootstrap.connect(bookieAddr);
    future.addListener(new ConnectionFutureListener(startTime));
    return future;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) LocalChannel(io.netty.channel.local.LocalChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) DecoderException(io.netty.handler.codec.DecoderException) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) BKException(org.apache.bookkeeper.client.BKException) SecurityException(org.apache.bookkeeper.tls.SecurityException) CorruptedFrameException(io.netty.handler.codec.CorruptedFrameException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) BookieSocketAddress(org.apache.bookkeeper.net.BookieSocketAddress) SocketAddress(java.net.SocketAddress) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder)

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