Skip to content

Instantly share code, notes, and snippets.

@pfreixes
Created July 18, 2017 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfreixes/13fedf2a589c260e6c7c64ae73653bb1 to your computer and use it in GitHub Desktop.
Save pfreixes/13fedf2a589c260e6c7c64ae73653bb1 to your computer and use it in GitHub Desktop.
package test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.nio.charset.Charset;
public class NettyTest {
public static void main(String[] args) throws Exception {
String host = args[0];
int port = Integer.parseInt(args[1]);
int sleepMillis = Integer.parseInt(args[2]);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap()
.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.out.println("channelActive");
try {
System.out.println("Sleeping...");
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("channelRead");
ByteBuf m = (ByteBuf) msg;
try {
int bytesAvaliable = m.readableBytes();
System.out.println(bytesAvaliable + " readable bytes in response buffer");
m.readBytes(bytesAvaliable);
System.out.println(m.getCharSequence(0, bytesAvaliable, Charset.defaultCharset()));
ctx.close();
} finally {
m.release();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
});
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
@pfreixes
Copy link
Author

Output

$ gradle shadowJar && java -jar build/libs/async-java-all.jar localhost 6379 10000
:compileJava UP-TO-DATE
:processResources NO-SOURCE
:classes UP-TO-DATE
:shadowJar UP-TO-DATE

BUILD SUCCESSFUL

Total time: 0.999 secs
log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
channelActive
Sleeping...
channelRead
36 readable bytes in response buffer
-ERR max number of clients reached```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment