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