Search in sources :

Example 66 with SocketChannel

use of 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 67 with SocketChannel

use of 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)

Example 68 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project cdap by caskdata.

the class NettyRouterPipelineTest method testHttpPipelining.

@Test
public void testHttpPipelining() throws Exception {
    final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
    EventLoopGroup eventGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpResponse) {
                        responseStatuses.add(((HttpResponse) msg).status());
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    // Create a connection and make five consecutive HTTP call without waiting for the first to respond
    Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
    for (int i = 0; i < 5; i++) {
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
        request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
        channel.writeAndFlush(request);
    }
    // Should get the first response as normal one
    HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpResponseStatus.OK, status);
    // The rest four should be failure responses
    for (int i = 0; i < 4; i++) {
        Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
    }
    eventGroup.shutdownGracefully();
    channel.close();
    Assert.assertTrue(responseStatuses.isEmpty());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 69 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project cdap by caskdata.

the class NettyRouter method createServerBootstrap.

private ServerBootstrap createServerBootstrap(final ChannelGroup channelGroup) throws ServiceBindException {
    EventLoopGroup bossGroup = createEventLoopGroup(serverBossThreadPoolSize, "router-server-boss-thread-%d");
    EventLoopGroup workerGroup = createEventLoopGroup(serverWorkerThreadPoolSize, "router-server-worker-thread-%d");
    return new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, serverConnectionBacklog).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            channelGroup.add(ch);
            ChannelPipeline pipeline = ch.pipeline();
            if (isSSLEnabled()) {
                pipeline.addLast("ssl", sslHandlerFactory.create(ch.alloc()));
            }
            pipeline.addLast("http-codec", new HttpServerCodec());
            pipeline.addLast("http-status-request-handler", new HttpStatusRequestHandler());
            if (securityEnabled) {
                pipeline.addLast("access-token-authenticator", new AuthenticationHandler(cConf, tokenValidator, discoveryServiceClient, accessTokenTransformer));
            }
            if (cConf.getBoolean(Constants.Router.ROUTER_AUDIT_LOG_ENABLED)) {
                pipeline.addLast("audit-log", new AuditLogHandler());
            }
            // Always let the client to continue sending the request body after the authentication passed
            pipeline.addLast("expect-continue", new HttpServerExpectContinueHandler());
            // for now there's only one hardcoded rule, but if there will be more, we may want it generic and configurable
            pipeline.addLast("http-request-handler", new HttpRequestRouter(cConf, serviceLookup));
        }
    });
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpServerExpectContinueHandler(io.netty.handler.codec.http.HttpServerExpectContinueHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpRequestRouter(co.cask.cdap.gateway.router.handlers.HttpRequestRouter) HttpStatusRequestHandler(co.cask.cdap.gateway.router.handlers.HttpStatusRequestHandler) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) AuditLogHandler(co.cask.cdap.gateway.router.handlers.AuditLogHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) AuthenticationHandler(co.cask.cdap.gateway.router.handlers.AuthenticationHandler)

Example 70 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project nuls by nuls-io.

the class BroadcastHandler method broadcast.

private BroadcastResult broadcast(NulsMessage message, Node node, boolean asyn) throws IOException {
    try {
        if (!node.isAlive() && node.getChannelId() == null) {
            return new BroadcastResult(false, "node not found");
        }
        SocketChannel channel = NioChannelMap.get(node.getChannelId());
        if (channel == null) {
            return new BroadcastResult(false, "node not found");
        }
        ChannelFuture future = channel.writeAndFlush(Unpooled.wrappedBuffer(message.serialize()));
        if (!asyn) {
            future.await();
            boolean success = future.isSuccess();
            if (!success) {
                return new BroadcastResult(false, "send message failed");
            }
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        Log.error(e);
        return new BroadcastResult(false, "send message failed");
    }
    return new BroadcastResult(true, "OK");
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) BroadcastResult(io.nuls.network.entity.BroadcastResult) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)235 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)101 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)94 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)94 Bootstrap (io.netty.bootstrap.Bootstrap)89 ChannelPipeline (io.netty.channel.ChannelPipeline)79 EventLoopGroup (io.netty.channel.EventLoopGroup)79 ChannelFuture (io.netty.channel.ChannelFuture)77 InetSocketAddress (java.net.InetSocketAddress)43 LoggingHandler (io.netty.handler.logging.LoggingHandler)42 Channel (io.netty.channel.Channel)35 IOException (java.io.IOException)33 SslContext (io.netty.handler.ssl.SslContext)30 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)29 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)29 ByteBuf (io.netty.buffer.ByteBuf)27 StringDecoder (io.netty.handler.codec.string.StringDecoder)23 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)15