Search in sources :

Example 56 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel 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 57 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel 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 58 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project bookkeeper by apache.

the class BookieNettyServer method listenOn.

private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress) throws InterruptedException {
    if (!conf.isDisableServerSocketBind()) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        bootstrap.group(eventLoopGroup, eventLoopGroup);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        if (eventLoopGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }
                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();
                // For ByteBufList, skip the usual LengthFieldPrepender and have the encoder itself to add it
                pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE);
                pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(contextHandler.getConnectionPeer(), authProviderFactory));
                ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);
                pipeline.addLast("contextHandler", contextHandler);
            }
        });
        // Bind and start to accept incoming connections
        Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel();
        if (listen.localAddress() instanceof InetSocketAddress) {
            if (conf.getBookiePort() == 0) {
                conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort());
            }
        }
    }
    if (conf.isEnableLocalTransport()) {
        ServerBootstrap jvmBootstrap = new ServerBootstrap();
        jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup);
        jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay());
        jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive());
        jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger());
        jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax()));
        if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) {
            jvmBootstrap.channel(LocalServerChannel.class);
        } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) {
            jvmBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            jvmBootstrap.channel(NioServerSocketChannel.class);
        }
        jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
                synchronized (suspensionLock) {
                    while (suspended) {
                        suspensionLock.wait();
                    }
                }
                BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler();
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
                pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
                pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry));
                pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry));
                pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler(contextHandler.getConnectionPeer(), authProviderFactory));
                ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler();
                pipeline.addLast("bookieRequestHandler", requestHandler);
                pipeline.addLast("contextHandler", contextHandler);
            }
        });
        // use the same address 'name', so clients can find local Bookie still discovering them using ZK
        jvmBootstrap.bind(bookieAddress.getLocalAddress()).sync();
        LocalBookiesRegistry.registerLocalBookieAddress(bookieAddress);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) LocalChannel(io.netty.channel.local.LocalChannel) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BookieException(org.apache.bookkeeper.bookie.BookieException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ChannelPipeline(io.netty.channel.ChannelPipeline) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup)

Example 59 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project jackrabbit-oak by apache.

the class ForwardHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    group = new NioEventLoopGroup(0, r -> {
        return new Thread(r, String.format("forward-handler-%d", threadNumber.getAndIncrement()));
    });
    Bootstrap b = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (flipPosition >= 0) {
                ch.pipeline().addLast(new FlipHandler(flipPosition));
            }
            if (skipBytes > 0) {
                ch.pipeline().addLast(new SkipHandler(skipPosition, skipBytes));
            }
            ch.pipeline().addLast(new BackwardHandler(ctx.channel()));
        }
    });
    remote = b.connect(targetHost, targetPort).sync().channel();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) LoggerFactory(org.slf4j.LoggerFactory) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) TimeUnit(java.util.concurrent.TimeUnit) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 60 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project ratpack by ratpack.

the class DefaultRatpackServer method buildChannel.

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter) throws InterruptedException {
    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));
    return serverBootstrap.group(execController.getEventLoopGroup()).channel(ChannelImplDetector.getServerSocketChannelImpl()).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());
            if (sslContext != null) {
                SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                pipeline.addLast("ssl", new SslHandler(sslEngine));
            }
            pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(), serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
            pipeline.addLast("adapter", handlerAdapter);
            ch.config().setAutoRead(false);
        }
    }).bind(buildSocketAddress(serverConfig)).sync().channel();
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslHandler(io.netty.handler.ssl.SslHandler) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ConnectionIdleTimeout(ratpack.http.internal.ConnectionIdleTimeout) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)283 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)114 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)107 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)105 Bootstrap (io.netty.bootstrap.Bootstrap)103 ChannelPipeline (io.netty.channel.ChannelPipeline)95 ChannelFuture (io.netty.channel.ChannelFuture)93 EventLoopGroup (io.netty.channel.EventLoopGroup)92 InetSocketAddress (java.net.InetSocketAddress)46 LoggingHandler (io.netty.handler.logging.LoggingHandler)45 IOException (java.io.IOException)44 Channel (io.netty.channel.Channel)42 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)36 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)35 SslContext (io.netty.handler.ssl.SslContext)34 ByteBuf (io.netty.buffer.ByteBuf)31 StringDecoder (io.netty.handler.codec.string.StringDecoder)27 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)20 ChannelInitializer (io.netty.channel.ChannelInitializer)19