netty笔记2-http服务器

通过netty可以实现一个简单的http服务器

一、httpserver接受请求

public class HttpServer {
    public static void main(String[] args) throws Exception {
        HttpServer server = new HttpServer();
        server.start(8000);
    }

    public void start(int port) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpResponseEncoder());
                            ch.pipeline().addLast(new HttpRequestDecoder());
                            ch.pipeline().addLast(new HttpObjectAggregator(10*1024*1024));
                            ch.pipeline().addLast(new HttpServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

二、handler处理逻辑

public class HttpServerHandler extends ChannelInboundHandlerAdapter {
    private String result = "";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FullHttpRequest)) {
            result = "未知请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        String uri = httpRequest.uri();
        String body = getBody(httpRequest);
        HttpMethod method = httpRequest.method();
        HttpHeaders headers = httpRequest.headers();

        if (!uri.startsWith("/test")) {
            System.out.println(uri);
            result = "非法请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        if (HttpMethod.GET.equals(method)) {
            //接受到的消息,做业务逻辑处理...
            System.out.println("body:" + body);
            for (Map.Entry<String, String> header : headers) {
                System.out.println(header);
            }
            result = String.format("%s请求,path=%s,body=%s",method.name(),uri,body);
            send(ctx, result, HttpResponseStatus.OK);
        }else if(HttpMethod.POST.equals(method)){
          Map<String,String>  resultMap = new HashMap<>();
          resultMap.put("method",method.name());
          resultMap.put("uri",uri);
          sendJson(ctx,JSON.toJSONString(resultMap),HttpResponseStatus.OK);
        } else {
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HTTP_1_1, OK, Unpooled.wrappedBuffer("OK OK OK OK"
                    .getBytes()));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().set(CONTENT_LENGTH,
                    response.content().readableBytes());
            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            ctx.write(response);
            ctx.flush();
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    /**
     * 发送response
     *
     * @param ctx
     * @param context
     * @param status
     */
    private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private void sendJson(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 获取body
     *
     * @param request
     * @return
     */
    private String getBody(FullHttpRequest request) {
        ByteBuf buf = request.content();
        return buf.toString(CharsetUtil.UTF_8);
    }
}

 参考:https://blog.csdn.net/wangshuang1631/article/details/73251180/

参考:https://blog.csdn.net/wayne_sulong/article/details/79423861

posted @ 2021-05-31 11:48  Mars.wang  阅读(89)  评论(0编辑  收藏  举报