代码改变世界

Netty实现http

2020-12-29 11:41  Tony、  阅读(150)  评论(0编辑  收藏  举报
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);
    }
}