use of io.netty.channel.DefaultEventLoopGroup in project netty by netty.
the class InboundHttp2ToHttpAdapterTest method boostrapEnv.
private void boostrapEnv(int clientLatchCount, int clientLatchCount2, int serverLatchCount, int serverLatchCount2, int settingsLatchCount) throws InterruptedException {
final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
clientDelegator = null;
serverDelegator = null;
serverConnectedChannel = null;
maxContentLength = 1024;
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
serverLatch = new CountDownLatch(serverLatchCount);
clientLatch = new CountDownLatch(clientLatchCount);
serverLatch2 = new CountDownLatch(serverLatchCount2);
clientLatch2 = new CountDownLatch(clientLatchCount2);
settingsLatch = new CountDownLatch(settingsLatchCount);
sb = new ServerBootstrap();
cb = new Bootstrap();
sb.group(new DefaultEventLoopGroup());
sb.channel(LocalServerChannel.class);
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
serverConnectedChannel = ch;
ChannelPipeline p = ch.pipeline();
Http2Connection connection = new DefaultHttp2Connection(true);
serverHandler = new Http2ConnectionHandlerBuilder().frameListener(new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength).validateHttpHeaders(true).propagateSettings(true).build()).connection(connection).gracefulShutdownTimeoutMillis(0).build();
p.addLast(serverHandler);
serverDelegator = new HttpResponseDelegator(serverListener, serverLatch, serverLatch2);
p.addLast(serverDelegator);
settingsDelegator = new HttpSettingsDelegator(settingsListener, settingsLatch);
p.addLast(settingsDelegator);
serverChannelLatch.countDown();
}
});
cb.group(new DefaultEventLoopGroup());
cb.channel(LocalChannel.class);
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
Http2Connection connection = new DefaultHttp2Connection(false);
clientHandler = new Http2ConnectionHandlerBuilder().frameListener(new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength).build()).connection(connection).gracefulShutdownTimeoutMillis(0).build();
p.addLast(clientHandler);
clientDelegator = new HttpResponseDelegator(clientListener, clientLatch, clientLatch2);
p.addLast(clientDelegator);
p.addLast(new ChannelHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Http2Exception e = getEmbeddedHttp2Exception(cause);
if (e != null) {
clientException = e;
clientLatch.countDown();
} else {
super.exceptionCaught(ctx, cause);
}
}
});
p.addLast(new ChannelInboundHandlerAdapter() {
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof Http2ConnectionPrefaceWrittenEvent) {
prefaceWrittenLatch.countDown();
ctx.pipeline().remove(this);
}
}
});
}
});
serverChannel = sb.bind(new LocalAddress("InboundHttp2ToHttpAdapterTest")).sync().channel();
ChannelFuture ccf = cb.connect(serverChannel.localAddress());
assertTrue(ccf.awaitUninterruptibly().isSuccess());
clientChannel = ccf.channel();
assertTrue(prefaceWrittenLatch.await(5, SECONDS));
assertTrue(serverChannelLatch.await(5, SECONDS));
}
use of io.netty.channel.DefaultEventLoopGroup in project netty by netty.
the class LocalEcho method main.
public static void main(String[] args) throws Exception {
// Address to bind on / connect to.
final LocalAddress addr = new LocalAddress(PORT);
EventLoopGroup serverGroup = new DefaultEventLoopGroup();
// NIO event loops are also OK
EventLoopGroup clientGroup = new NioEventLoopGroup();
try {
// Note that we can use any event loop to ensure certain local channels
// are handled by the same event loop thread which drives a certain socket channel
// to reduce the communication latency between socket channels and local channels.
ServerBootstrap sb = new ServerBootstrap();
sb.group(serverGroup).channel(LocalServerChannel.class).handler(new ChannelInitializer<LocalServerChannel>() {
@Override
public void initChannel(LocalServerChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
}
}).childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
}
});
Bootstrap cb = new Bootstrap();
cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
}
});
// Start the server.
sb.bind(addr).sync();
// Start the client.
Channel ch = cb.connect(addr).sync().channel();
// Read commands from the stdin.
System.out.println("Enter text (quit to end)");
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (; ; ) {
String line = in.readLine();
if (line == null || "quit".equalsIgnoreCase(line)) {
break;
}
// Sends the received line to the server.
lastWriteFuture = ch.writeAndFlush(line);
}
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
lastWriteFuture.awaitUninterruptibly();
}
} finally {
serverGroup.shutdownGracefully();
clientGroup.shutdownGracefully();
}
}
use of io.netty.channel.DefaultEventLoopGroup in project netty by netty.
the class SniClientTest method testSniClient.
private static void testSniClient(SslProvider sslClientProvider, SslProvider sslServerProvider) throws Exception {
final String sniHost = "sni.netty.io";
LocalAddress address = new LocalAddress("test");
EventLoopGroup group = new DefaultEventLoopGroup(1);
Channel sc = null;
Channel cc = null;
try {
SelfSignedCertificate cert = new SelfSignedCertificate();
final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(sslServerProvider).build();
final Promise<String> promise = group.next().newPromise();
ServerBootstrap sb = new ServerBootstrap();
sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addFirst(new SniHandler(new Mapping<String, SslContext>() {
@Override
public SslContext map(String input) {
promise.setSuccess(input);
return sslServerContext;
}
}));
}
}).bind(address).syncUninterruptibly().channel();
SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider).build();
Bootstrap cb = new Bootstrap();
cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
Assert.assertEquals(sniHost, promise.syncUninterruptibly().getNow());
} finally {
if (cc != null) {
cc.close().syncUninterruptibly();
}
if (sc != null) {
sc.close().syncUninterruptibly();
}
group.shutdownGracefully();
}
}
use of io.netty.channel.DefaultEventLoopGroup in project netty by netty.
the class SniHandlerTest method testReplaceHandler.
@Test(timeout = 30000)
public void testReplaceHandler() throws Exception {
switch(provider) {
case OPENSSL:
case OPENSSL_REFCNT:
final String sniHost = "sni.netty.io";
LocalAddress address = new LocalAddress("testReplaceHandler-" + Math.random());
EventLoopGroup group = new DefaultEventLoopGroup(1);
Channel sc = null;
Channel cc = null;
SslContext sslContext = null;
SelfSignedCertificate cert = new SelfSignedCertificate();
try {
final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(provider).build();
final Mapping<String, SslContext> mapping = new Mapping<String, SslContext>() {
@Override
public SslContext map(String input) {
return sslServerContext;
}
};
final Promise<Void> releasePromise = group.next().newPromise();
final SniHandler handler = new SniHandler(mapping) {
@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, final SslContext sslContext) throws Exception {
boolean success = false;
try {
// The SniHandler's replaceHandler() method allows us to implement custom behavior.
// As an example, we want to release() the SslContext upon channelInactive() or rather
// when the SslHandler closes it's SslEngine. If you take a close look at SslHandler
// you'll see that it's doing it in the #handlerRemoved0() method.
SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
try {
SslHandler customSslHandler = new CustomSslHandler(sslContext, sslEngine) {
@Override
public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
try {
super.handlerRemoved0(ctx);
} finally {
releasePromise.trySuccess(null);
}
}
};
ctx.pipeline().replace(this, CustomSslHandler.class.getName(), customSslHandler);
success = true;
} finally {
if (!success) {
ReferenceCountUtil.safeRelease(sslEngine);
}
}
} finally {
if (!success) {
ReferenceCountUtil.safeRelease(sslContext);
releasePromise.cancel(true);
}
}
}
};
ServerBootstrap sb = new ServerBootstrap();
sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addFirst(handler);
}
}).bind(address).syncUninterruptibly().channel();
sslContext = SslContextBuilder.forClient().sslProvider(provider).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
Bootstrap cb = new Bootstrap();
cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
cc.writeAndFlush(Unpooled.wrappedBuffer("Hello, World!".getBytes())).syncUninterruptibly();
// Notice how the server's SslContext refCnt is 1
assertEquals(1, ((ReferenceCounted) sslServerContext).refCnt());
// The client disconnects
cc.close().syncUninterruptibly();
if (!releasePromise.awaitUninterruptibly(10L, TimeUnit.SECONDS)) {
throw new IllegalStateException("It doesn't seem #replaceHandler() got called.");
}
// We should have successfully release() the SslContext
assertEquals(0, ((ReferenceCounted) sslServerContext).refCnt());
} finally {
if (cc != null) {
cc.close().syncUninterruptibly();
}
if (sc != null) {
sc.close().syncUninterruptibly();
}
if (sslContext != null) {
ReferenceCountUtil.release(sslContext);
}
group.shutdownGracefully();
cert.delete();
}
case JDK:
return;
default:
throw new Error();
}
}
use of io.netty.channel.DefaultEventLoopGroup in project netty by netty.
the class LocalTransportThreadModelTest method testConcurrentMessageBufferAccess.
@Test(timeout = 30000)
@Ignore
public void testConcurrentMessageBufferAccess() throws Throwable {
EventLoopGroup l = new DefaultEventLoopGroup(4, new DefaultThreadFactory("l"));
EventExecutorGroup e1 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e1"));
EventExecutorGroup e2 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e2"));
EventExecutorGroup e3 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e3"));
EventExecutorGroup e4 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e4"));
EventExecutorGroup e5 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e5"));
try {
final MessageForwarder1 h1 = new MessageForwarder1();
final MessageForwarder2 h2 = new MessageForwarder2();
final MessageForwarder3 h3 = new MessageForwarder3();
final MessageForwarder1 h4 = new MessageForwarder1();
final MessageForwarder2 h5 = new MessageForwarder2();
final MessageDiscarder h6 = new MessageDiscarder();
final Channel ch = new LocalChannel();
// inbound: int -> byte[4] -> int -> int -> byte[4] -> int -> /dev/null
// outbound: int -> int -> byte[4] -> int -> int -> byte[4] -> /dev/null
ch.pipeline().addLast(h1).addLast(e1, h2).addLast(e2, h3).addLast(e3, h4).addLast(e4, h5).addLast(e5, h6);
l.register(ch).sync().channel().connect(localAddr).sync();
final int ROUNDS = 1024;
final int ELEMS_PER_ROUNDS = 8192;
final int TOTAL_CNT = ROUNDS * ELEMS_PER_ROUNDS;
for (int i = 0; i < TOTAL_CNT; ) {
final int start = i;
final int end = i + ELEMS_PER_ROUNDS;
i = end;
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
for (int j = start; j < end; j++) {
ch.pipeline().fireChannelRead(Integer.valueOf(j));
}
}
});
}
while (h1.inCnt < TOTAL_CNT || h2.inCnt < TOTAL_CNT || h3.inCnt < TOTAL_CNT || h4.inCnt < TOTAL_CNT || h5.inCnt < TOTAL_CNT || h6.inCnt < TOTAL_CNT) {
if (h1.exception.get() != null) {
throw h1.exception.get();
}
if (h2.exception.get() != null) {
throw h2.exception.get();
}
if (h3.exception.get() != null) {
throw h3.exception.get();
}
if (h4.exception.get() != null) {
throw h4.exception.get();
}
if (h5.exception.get() != null) {
throw h5.exception.get();
}
if (h6.exception.get() != null) {
throw h6.exception.get();
}
Thread.sleep(10);
}
for (int i = 0; i < TOTAL_CNT; ) {
final int start = i;
final int end = i + ELEMS_PER_ROUNDS;
i = end;
ch.pipeline().context(h6).executor().execute(new Runnable() {
@Override
public void run() {
for (int j = start; j < end; j++) {
ch.write(Integer.valueOf(j));
}
ch.flush();
}
});
}
while (h1.outCnt < TOTAL_CNT || h2.outCnt < TOTAL_CNT || h3.outCnt < TOTAL_CNT || h4.outCnt < TOTAL_CNT || h5.outCnt < TOTAL_CNT || h6.outCnt < TOTAL_CNT) {
if (h1.exception.get() != null) {
throw h1.exception.get();
}
if (h2.exception.get() != null) {
throw h2.exception.get();
}
if (h3.exception.get() != null) {
throw h3.exception.get();
}
if (h4.exception.get() != null) {
throw h4.exception.get();
}
if (h5.exception.get() != null) {
throw h5.exception.get();
}
if (h6.exception.get() != null) {
throw h6.exception.get();
}
Thread.sleep(10);
}
ch.close().sync();
} finally {
l.shutdownGracefully();
e1.shutdownGracefully();
e2.shutdownGracefully();
e3.shutdownGracefully();
e4.shutdownGracefully();
e5.shutdownGracefully();
l.terminationFuture().sync();
e1.terminationFuture().sync();
e2.terminationFuture().sync();
e3.terminationFuture().sync();
e4.terminationFuture().sync();
e5.terminationFuture().sync();
}
}
Aggregations