Skip to content

Instantly share code, notes, and snippets.

@md-5
Created September 6, 2012 10:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save md-5/3654232 to your computer and use it in GitHub Desktop.
Save md-5/3654232 to your computer and use it in GitHub Desktop.
Why Netty is awesome.
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();
}
}
@prprprus
Copy link

The code like a JS callback hell...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment