Created
September 6, 2012 10:03
-
-
Save md-5/3654232 to your computer and use it in GitHub Desktop.
Why Netty is awesome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.md_5.jcaptive; | |
import io.netty.bootstrap.Bootstrap; | |
import io.netty.bootstrap.ServerBootstrap; | |
import io.netty.channel.Channel; | |
import io.netty.channel.ChannelFuture; | |
import io.netty.channel.ChannelFutureListener; | |
import io.netty.channel.ChannelHandlerContext; | |
import io.netty.channel.ChannelInboundMessageHandlerAdapter; | |
import io.netty.channel.ChannelInitializer; | |
import io.netty.channel.socket.nio.NioEventLoopGroup; | |
import io.netty.channel.socket.nio.NioServerSocketChannel; | |
import io.netty.channel.socket.nio.NioSocketChannel; | |
import io.netty.handler.codec.http.HttpClientCodec; | |
import io.netty.handler.codec.http.HttpRequest; | |
import io.netty.handler.codec.http.HttpResponse; | |
import io.netty.handler.codec.http.HttpServerCodec; | |
public class App { | |
public static void main(String[] args) { | |
new ServerBootstrap().channel(new NioServerSocketChannel()).childHandler(new ChannelInitializer() { | |
@Override | |
public void initChannel(Channel ch) throws Exception { | |
ch.pipeline().addLast(new HttpServerCodec(), new ChannelInboundMessageHandlerAdapter<HttpRequest>() { | |
@Override | |
public void messageReceived(final ChannelHandlerContext client, final HttpRequest request) throws Exception { | |
String[] header = request.getHeader("Host").split(":", 2); | |
new Bootstrap().channel(new NioSocketChannel()).group(new NioEventLoopGroup()).remoteAddress(header[0], header.length == 2 ? Integer.parseInt(header[1]) : 80).handler(new ChannelInitializer() { | |
@Override | |
public void initChannel(Channel ch) throws Exception { | |
ch.pipeline().addLast(new HttpClientCodec(), new ChannelInboundMessageHandlerAdapter<HttpResponse>() { | |
@Override | |
public void messageReceived(ChannelHandlerContext server, HttpResponse response) throws Exception { | |
client.write(response).addListener(ChannelFutureListener.CLOSE); | |
} | |
}); | |
} | |
}).connect().addListener(new ChannelFutureListener() { | |
public void operationComplete(ChannelFuture future) throws Exception { | |
future.channel().write(request); | |
} | |
}); | |
} | |
}); | |
} | |
}).group(new NioEventLoopGroup()).localAddress(7777).bind(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code like a JS callback hell...