我正在实现一个接受HTTP请求并执行一些业务逻辑的Netty服务器
基本上,我接受localhost / hello和sysout uri is hello
运行服务器时,在CustomRequestHandler#channelRead0方法中看不到任何sysout。 我一直打开调试器,但没有看到channelRead0方法被调用。 我不知道是什么问题
我正在使用Netty 4.1.30。最终版
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());
}
}
答案 0 :(得分:1)
问题是您使用了:
.childOption(ChannelOption.AUTO_READ, false);
这意味着,一旦频道被接受,它会在您每次要处理更多入站数据时调用ctx.read()
之前不会处理任何传入数据。
因此,您可以选择删除此行,也可以覆盖channelActive(...)
中的CustomRequestHandler
并在那里调用ctx.read()
。这将确保您尝试读取一些入站数据。也就是说,要处理更多数据时,您将需要再次调用ctx.read()
。