Skip to content

Instantly share code, notes, and snippets.

@danveloper
Created Jan 15, 2015
Embed
What would you like to do?
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

danveloper commented Jan 15, 2015

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