不同url的Netty处理程序



我有一个简单的netty4服务器和一个处理程序:

public class UploadServer {
private final int port;
public UploadServer(int port) {
    this.port = port;
}
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer());
        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
public static void main(String[] args) throws Exception {
    int port;
    if (args.length > 0) {
        port = Integer.parseInt(args[0]);
    } else {
        port = 8080;
    }
    new UploadServer(port).run();
}
private class ServerInitializer extends ChannelInitializer<SocketChannel>{
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast("decoder", new HttpRequestDecoder());
        p.addLast("encoder", new HttpResponseEncoder());
        p.addLast("handler", new UploadServerHandler());
    }
}

和这个处理程序

public class UploadServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
    System.out.println("HEllO");
}

}

我有两个问题:

  • 如果我启动这个项目并在浏览器中转到localhost:8080,我看到"HEllO"在控制台中出现两次。
  • 我想知道如何实现映射不同的处理程序为不同的url在我的uploadServerHandler

不好意思

控制台中出现的两个"Hello"可能与浏览器正在进行两个调用有关,一个调用index.html,另一个调用favicon。

您可以使用curl或wget来避免请求图标。

对于url映射不同的处理程序,我这样做的方式(不确定这是最好的方式),是我在主处理程序中获得URI:

  String uri = request.getUri();

,然后对已知的URI进行测试,并相应地重定向到其他处理程序。

最新更新