1. 程式人生 > 實用技巧 >Netty實現http

Netty實現http

public class HttpServer2 {
    public static void main(String[] args) throws Exception {
        new HttpServer2(8084).start();
    }

    int port;

    public HttpServer2(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss 
= new NioEventLoopGroup(); EventLoopGroup work = new NioEventLoopGroup(); bootstrap.group(boss, work) //.handler(new LoggingHandler(LogLevel.DEBUG)) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast(new HttpServerCodec());// http 編解碼 pipeline.addLast(new HttpRequestDecoder());// http 編解碼 pipeline.addLast(new
HttpResponseEncoder()); // pipeline.addLast("httpAggregator", new HttpObjectAggregator(512 * 1024)); // http 訊息聚合器 512*1024為接收的最大contentlength pipeline.addLast(new HttpRequestHandler());// 請求處理器 pipeline.addLast(new MyRequestHandler()); } }); ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync(); System.out.println(" server start up on port : " + port); f.channel().closeFuture().sync(); }
public class MyRequestHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!(msg instanceof DefaultHttpRequest)) {
            return;
        }
        String uri = "/a";//req.uri();

        String msg1 = "<html><head><title>test</title></head><body>你請求uri為:" + uri + "</body></html>";
        // 建立http響應
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(msg1, CharsetUtil.UTF_8));
        // 設定頭資訊
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg1.getBytes().length);

        ctx.writeAndFlush(response);//.addListener(ChannelFutureListener.CLOSE);
    }
}