I am implementing a netty server that accepts http request and do some business logic
Basically, I accept GET request on localhost/hello and sysout uri is hello
when I run the server, I do not see any of sysouts in CustomRequestHandler#channelRead0 method. I kept the debugger on and I see the channelRead0 method is not getting invoked. I cannot figure out what the problem is
I am using Netty 4.1.30.Final version
public class HttpServer {
public static void main( String[] args ) throws Exception {
InetSocketAddress tcpSocketAddress = new InetSocketAddress(8080);
System.out.println("Starting http server at " + tcpSocketAddress.getPort());
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new MyChannelInitializer())
.childOption(ChannelOption.AUTO_READ, false);
ChannelFuture serverChannelFuture = bootstrap.bind(tcpSocketAddress).sync();
System.out.println("open the browser");
serverChannelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class MyChannelIntializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
//p.addLast(new HttpServerCodec());
p.addLast(new HttpRequestDecoder());
p.addLast(new HttpResponseEncoder());
p.addLast(new CustomRequestHandler());
}
}
public class CustomRequestHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object httpObject) {
System.out.println("hello world");
if (httpObject instanceof HttpRequest) {
HttpRequest request = (HttpRequest) httpObject;
System.out.println("uri is " + request.getUri());
}
}
The problem is that you use :
This means once a channel is accepted it will not process any incoming data until you call
ctx.read()
every time you want to process more inbound data.So your options are either to remove this line or override
channelActive(...)
as well in yourCustomRequestHandler
and callctx.read()
there. This will ensure you will try to read some inbound data. That said you will need to callctx.read()
again when you want to process more data.