简体   繁体   English

不同URL的Netty处理程序

[英]Netty handlers for different URLs

I have a simple netty4 server with one handler : 我有一台带有一个处理程序的简单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());
    }
}

and this handler 和这个处理程序

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

} }

And I have two problems: 我有两个问题:

  • if I start this project and go to localhost:8080 in the browser I see "HEllO" twice in the console. 如果我启动此项目并在浏览器中转到localhost:8080,则在控制台中会两次看到“ HEllO”。
  • I want know how to implement mapping different handlers for different URLs in my uploadServerHandler 我想知道如何在我的uploadServerHandler中为不同的URL实现映射不同的处理程序

sorry for bad English 对不起,英语不好

The two "Hello" in the console are probably related to the fact that your browser is making two calls, one for index.html and the other for the favicon. 控制台中的两个“ Hello”可能与以下事实有关:浏览器正在进行两个调用,一个调用index.html,另一个调用favicon。

You can use curl or wget to avoid requesting the favicon. 您可以使用curl或wget避免请求图标。

For url mapping different handlers, the way I do it (not sure that it is the best way though), is that I get the URI in the main handler with: 对于url映射不同的处理程序,我这样做的方式(虽然不能确定这是最好的方式),是通过以下方式在主处理程序中获取URI:

  String uri = request.getUri();

and then test the URI against my knwown URIs and redirect to other handlers accordingly. 然后针对我的已知URI测试URI,并相应地重定向到其他处理程序。

Java have a look at this once. Java的看看一次。 Let me know is this what you are looking for ? 让我知道这是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM