• 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

  • 相关阅读:
    结对第一次—原型设计(文献摘要热词统计)
    第一次作业-准备篇
    软件工程实践总结
    团队作业第二次—项目选题报告
    软工实践|结对第二次—文献摘要热词统计
    软工实践|结对第一次—原型设计(文献摘要热词统计)
    第一次作业-准备篇
    个人作业——软件工程实践总结作业
    团队作业第二次——项目选题报告
    结对第二次—文献摘要热词统计
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/14830751.html
Copyright © 2020-2023  润新知