mechanikos mechanikos - 1 year ago 128
Java Question

Netty handlers for different URLs

I have a simple netty4 server with one handler :

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();, workerGroup)
.childHandler(new ServerInitializer());
Channel ch = b.bind(port).sync().channel();
} finally {

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>{
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> {
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {


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.

  • I want know how to implement mapping different handlers for different URLs in my uploadServerHandler

sorry for bad English

Answer Source

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.

You can use curl or wget to avoid requesting the favicon.

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:

  String uri = request.getUri();

and then test the URI against my knwown URIs and redirect to other handlers accordingly.