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();
}
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;
}
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;
}
}
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);
}
}
});
}
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;
}
Aggregations