Search in sources :

Example 21 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.getSslContext();
    boolean requireClientSslAuth = serverConfig.isRequireClientSslAuth();
    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);
    });
    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();
            if (sslContext != null) {
                SSLEngine sslEngine = sslContext.createSSLEngine();
                sslEngine.setUseClientMode(false);
                sslEngine.setNeedClientAuth(requireClientSslAuth);
                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) SSLContext(javax.net.ssl.SSLContext) 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)

Example 22 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project spring-framework by spring-projects.

the class Netty4ClientHttpRequestFactory method buildBootstrap.

private Bootstrap buildBootstrap(URI uri, boolean isSecure) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            configureChannel(channel.config());
            ChannelPipeline pipeline = channel.pipeline();
            if (isSecure) {
                Assert.notNull(sslContext, "sslContext should not be null");
                pipeline.addLast(sslContext.newHandler(channel.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
            if (readTimeout > 0) {
                pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
            }
        }
    });
    return bootstrap;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) Bootstrap(io.netty.bootstrap.Bootstrap) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 23 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project pulsar by yahoo.

the class MockBrokerService method startMockBrokerService.

public void startMockBrokerService() throws Exception {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
    final int numThreads = 2;
    final int MaxMessageSize = 5 * 1024 * 1024;
    EventLoopGroup eventLoopGroup;
    try {
        if (SystemUtils.IS_OS_LINUX) {
            try {
                eventLoopGroup = new EpollEventLoopGroup(numThreads, threadFactory);
            } catch (UnsatisfiedLinkError e) {
                eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
            }
        } else {
            eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
        }
        workerGroup = eventLoopGroup;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup, workerGroup);
        if (workerGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                ch.pipeline().addLast("handler", new MockServerCnx());
            }
        });
        // Bind and start to accept incoming connections.
        bootstrap.bind(brokerServicePort).sync();
    } catch (Exception e) {
        throw e;
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 24 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project riposte by Nike-Inc.

the class Server method startup.

public void startup() throws CertificateException, IOException, InterruptedException {
    if (startedUp) {
        throw new IllegalArgumentException("This Server instance has already started. " + "You can only call startup() once");
    }
    // Figure out what port to bind to.
    int port = Integer.parseInt(System.getProperty("endpointsPort", serverConfig.isEndpointsUseSsl() ? String.valueOf(serverConfig.endpointsSslPort()) : String.valueOf(serverConfig.endpointsPort())));
    // Configure SSL if desired.
    final SslContext sslCtx;
    if (serverConfig.isEndpointsUseSsl()) {
        sslCtx = serverConfig.createSslContext();
    } else {
        sslCtx = null;
    }
    // Configure the server
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    Class<? extends ServerChannel> channelClass;
    //      NIO event loop group.
    if (Epoll.isAvailable()) {
        logger.info("The epoll native transport is available. Using epoll instead of NIO. " + "riposte_server_using_native_epoll_transport=true");
        bossGroup = (serverConfig.bossThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numBossThreads()) : new EpollEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
        workerGroup = (serverConfig.workerThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numWorkerThreads()) : new EpollEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
        channelClass = EpollServerSocketChannel.class;
    } else {
        logger.info("The epoll native transport is NOT available or you are not running on a compatible " + "OS/architecture. Using NIO. riposte_server_using_native_epoll_transport=false");
        bossGroup = (serverConfig.bossThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numBossThreads()) : new NioEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
        workerGroup = (serverConfig.workerThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numWorkerThreads()) : new NioEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
        channelClass = NioServerSocketChannel.class;
    }
    eventLoopGroups.add(bossGroup);
    eventLoopGroups.add(workerGroup);
    // Figure out which channel initializer should set up the channel pipelines for new channels.
    ChannelInitializer<SocketChannel> channelInitializer = serverConfig.customChannelInitializer();
    if (channelInitializer == null) {
        // No custom channel initializer, so use the default
        channelInitializer = new HttpChannelInitializer(sslCtx, serverConfig.maxRequestSizeInBytes(), serverConfig.appEndpoints(), serverConfig.requestAndResponseFilters(), serverConfig.longRunningTaskExecutor(), serverConfig.riposteErrorHandler(), serverConfig.riposteUnhandledErrorHandler(), serverConfig.requestContentValidationService(), serverConfig.defaultRequestContentDeserializer(), new ResponseSender(serverConfig.defaultResponseContentSerializer(), serverConfig.errorResponseBodySerializer()), serverConfig.metricsListener(), serverConfig.defaultCompletableFutureTimeoutInMillisForNonblockingEndpoints(), serverConfig.accessLogger(), serverConfig.pipelineCreateHooks(), serverConfig.requestSecurityValidator(), serverConfig.workerChannelIdleTimeoutMillis(), serverConfig.proxyRouterConnectTimeoutMillis(), serverConfig.incompleteHttpCallTimeoutMillis(), serverConfig.maxOpenIncomingServerChannels(), serverConfig.isDebugChannelLifecycleLoggingEnabled(), serverConfig.userIdHeaderKeys());
    }
    // Create the server bootstrap
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(channelClass).childHandler(channelInitializer);
    // execute pre startup hooks
    if (serverConfig.preServerStartupHooks() != null) {
        for (PreServerStartupHook hook : serverConfig.preServerStartupHooks()) {
            hook.executePreServerStartupHook(b);
        }
    }
    if (serverConfig.isDebugChannelLifecycleLoggingEnabled())
        b.handler(new LoggingHandler(SERVER_BOSS_CHANNEL_DEBUG_LOGGER_NAME, LogLevel.DEBUG));
    // Bind the server to the desired port and start it up so it is ready to receive requests
    Channel ch = b.bind(port).sync().channel();
    // execute post startup hooks
    if (serverConfig.postServerStartupHooks() != null) {
        for (PostServerStartupHook hook : serverConfig.postServerStartupHooks()) {
            hook.executePostServerStartupHook(serverConfig, ch);
        }
    }
    channels.add(ch);
    logger.info("Server channel open and accepting " + (serverConfig.isEndpointsUseSsl() ? "https" : "http") + " requests on port " + port);
    startedUp = true;
    // Add a shutdown hook so we can gracefully stop the server when the JVM is going down
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                shutdown();
            } catch (Exception e) {
                logger.warn("Error shutting down Riposte", e);
            }
        }
    });
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ResponseSender(com.nike.riposte.server.http.ResponseSender) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) HttpChannelInitializer(com.nike.riposte.server.channelpipeline.HttpChannelInitializer) PostServerStartupHook(com.nike.riposte.server.hooks.PostServerStartupHook) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) PreServerStartupHook(com.nike.riposte.server.hooks.PreServerStartupHook)

Example 25 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project pulsar by yahoo.

the class DiscoveryServiceTest method connectToService.

/**
     * creates ClientHandler channel to connect and communicate with server
     * 
     * @param serviceUrl
     * @param latch
     * @return
     * @throws URISyntaxException
     */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PrivateKey(java.security.PrivateKey) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)65 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 ChannelPipeline (io.netty.channel.ChannelPipeline)31 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)28 Bootstrap (io.netty.bootstrap.Bootstrap)27 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)24 ChannelFuture (io.netty.channel.ChannelFuture)22 EventLoopGroup (io.netty.channel.EventLoopGroup)21 Channel (io.netty.channel.Channel)17 SslContext (io.netty.handler.ssl.SslContext)15 IOException (java.io.IOException)14 InetSocketAddress (java.net.InetSocketAddress)14 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)9 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)7 ByteBuf (io.netty.buffer.ByteBuf)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6 ChannelInitializer (io.netty.channel.ChannelInitializer)6