Skip to content

Instantly share code, notes, and snippets.

@danveloper
Created January 15, 2015 16:05
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 danveloper/5bd833cd78e8bdba966c to your computer and use it in GitHub Desktop.
Save danveloper/5bd833cd78e8bdba966c to your computer and use it in GitHub Desktop.
Netty Read Channel Only When I Want To
public static void main(String[] args) throws Exception {
EventLoopGroup elg = new NioEventLoopGroup();
Bootstrap b = new Bootstrap()
.group(elg)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.config().setAutoRead(false);
ch.pipeline()
.addLast("framer", new FixedLengthFrameDecoder(100))
.addLast("decoder", new StringDecoder())
.addLast("encoder", new StringEncoder())
.addLast("handler", new ClientHandler());
}
});
ChannelFuture f = b.connect(HOST, PORT);
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
final Channel ch = f.channel();
ByteBuf buf = ch.alloc().buffer()
.writeBytes(Unpooled.copiedBuffer(String.format("GET %s HTTP/1.1\nHost: %s\r\n\n", PATH, HOST),
Charset.defaultCharset()));
ChannelFuture w = ch.writeAndFlush(buf);
w.addListener(w1 -> {
if (w.isSuccess()) {
ch.read();
}
});
}
}
});
new CountDownLatch(1).await();
}
@danveloper
Copy link
Author

You can ignore the "GET %s HTTP/1.1\nHost: %s\r\n\n" line... This is just for testing streaming (web servers are handy :-))

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