3、Netty HTTP协议开发

关于HTTP的介绍,参见HTTP协议介绍

FileServer应用开发

Netty HTTP服务端开发:

public class HttpFileServer {

    private static final String DEFAULT_URL = "/src/main/java/com/kim/";

    private static String ip = "10.200.88.159";

    static {
        try {
            //获取本地IP
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public void run(final int port, final String url) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {
                            //添加请求消息解码器,对HTTP 请求解码
                            ch.pipeline().addLast("http-decoder",
                                    new HttpRequestDecoder());
                            //添加HttpObjectAggregator解码器,将多个消息转为单一的FullHttpRequest或者FullHttpResponse
                            //因为HTTP解码器会在每个HTTP消息中生成多个消息对象:
                            /*
                            1、HttpRequest/HttpResponse
                            2、HttpContent
                            3、LastHttpContent
                             */
                            ch.pipeline().addLast("http-aggregator",
                                    new HttpObjectAggregator(65536));
                            //添加响应编码器
                            ch.pipeline().addLast("http-encoder",
                                    new HttpResponseEncoder());
                            //ChunkedWriteHandler支持异步传输大的码流(例如大的文件传输),不占用过多内存,防止内存溢出
                            ch.pipeline().addLast("http-chunked",
                                    new ChunkedWriteHandler());
                            //添加文件服务器业务处理器
                            ch.pipeline().addLast("fileServerHandler",
                                    new HttpFileServerHandler(url));
                        }
                    });
            ChannelFuture future = b.bind(ip, port).sync();
            System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://" + ip + ":"
                    + port + url);
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        String url = DEFAULT_URL;
        if (args.length > 1) {
            url = args[1];
        }
        new HttpFileServer().run(port, url);
    }
}
public class HttpFileServerHandler extends
        SimpleChannelInboundHandler<FullHttpRequest> {
    private final String url;

    public HttpFileServerHandler(String url) {
        this.url = url;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx,
                                FullHttpRequest request) throws Exception {
        //解码失败,返回400,客户端请求错误
        if (!request.decoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST);
            return;
        }
        //只能接收GET请求
        if (request.method() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }
        //获取和构造URI,返回资源定位符
        final String uri = request.uri();
        final String path = sanitizeUri(uri);
        //如果路径不合法,返回403
        if (path == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        //如果文件不存在或者是隐藏文件,返回404
        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        //如果是目录,发送目录的链接给浏览器
        if (file.isDirectory()) {
            if (uri.endsWith("/")) {
                sendListing(ctx, file);
            } else {
                sendRedirect(ctx, uri + '/');
            }
            return;
        }
        //如果不是个文件,返回403
        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        RandomAccessFile randomAccessFile = null;
        try {
            //使用随机文件读写类以只读的方式打开文件
            randomAccessFile = new RandomAccessFile(file, "r");// 以只读的方式打开文件
        } catch (FileNotFoundException fnfe) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        //获取文件的长度
        long fileLength = randomAccessFile.length();
        //构造成功的http应答消息
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        //消息头中设置content length和 content type
        setContentLength(response, fileLength);
        setContentTypeHeader(response, file);
        //判断是否是KeepAlive
        if (isKeepAlive(request)) {
            //如果是,在应答消息头中设置connection为keepalive
            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //将响应头写入channel,发送响应消息
        ctx.write(response);
        ChannelFuture sendFileFuture;
        //通过Netty的ChunkedFile对象直接将文件写入到发送缓冲区
        sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0,
                fileLength, 8192), ctx.newProgressivePromise());
        //为sendFileFuture添加GenericFutureListener
        sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future,
                                            long progress, long total) {
                if (total < 0) { // total unknown
                    System.err.println("Transfer progress: " + progress);
                } else {
                    System.err.println("Transfer progress: " + progress + " / "
                            + total);
                }
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future)
                    throws Exception {
                //如果发送完成,打印Transfer complete.
                System.out.println("Transfer complete.");
            }
        });
        //如果使用chunked编码,最后需要发送一个编码结束的空消息体,将LastHttpContent.EMPTY_LAST_CONTENT发送到缓冲区中,标识所有的消息体已经发送完成
        //同时调用flush方法将之前在发送缓冲区的消息刷新到SocketChannel中发送给对方
        ChannelFuture lastContentFuture = ctx
                .writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        //如果是非keepalive的,最后一包消息发送完之后,服务端要主动关闭连接
        if (!isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }

    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

    private String sanitizeUri(String uri) {
        try {
            //对uri解码
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            try {
                uri = URLDecoder.decode(uri, "ISO-8859-1");
            } catch (UnsupportedEncodingException e1) {
                throw new Error();
            }
        }
        //解码成功,对uri进行合法性判断
        if (!uri.startsWith(url)) {
            return null;
        }
        if (!uri.startsWith("/")) {
            return null;
        }
        //将分隔符替换为操作系统文件路径分隔符
        uri = uri.replace('/', File.separatorChar);
        if (uri.contains(File.separator + '.')
                || uri.contains('.' + File.separator) || uri.startsWith(".")
                || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) {
            return null;
        }
        //对文件路径拼接,当前运行程序所在的工程目录+uri的绝对路径
        return System.getProperty("user.dir") + File.separator + uri;
    }

    private static final Pattern ALLOWED_FILE_NAME = Pattern
            .compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");

    private static void sendListing(ChannelHandlerContext ctx, File dir) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        StringBuilder buf = new StringBuilder();
        String dirPath = dir.getPath();
        buf.append("<!DOCTYPE html>\r\n");
        buf.append("<html><head><title>");
        buf.append(dirPath);
        buf.append(" 目录:");
        buf.append("</title></head><body>\r\n");
        buf.append("<h3>");
        buf.append(dirPath).append(" 目录:");
        buf.append("</h3>\r\n");
        buf.append("<ul>");
        buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
        for (File f : dir.listFiles()) {
            if (f.isHidden() || !f.canRead()) {
                continue;
            }
            String name = f.getName();
            if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                continue;
            }
            buf.append("<li>链接:<a href=\"");
            buf.append(name);
            buf.append("\">");
            buf.append(name);
            buf.append("</a></li>\r\n");
        }
        buf.append("</ul></body></html>\r\n");
        //分配对应消息的缓冲对象
        ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
        //将缓冲区中的响应消息存放到HTTP的应答消息中
        response.content().writeBytes(buffer);
        //释放缓冲区
        buffer.release();
        //将响应消息发送到缓冲区,并刷新到SocketChannel
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, newUri);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendError(ChannelHandlerContext ctx,
                                  HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                status, Unpooled.copiedBuffer("Failure: " + status.toString()
                + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void setContentTypeHeader(HttpResponse response, File file) {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        response.headers().set(CONTENT_TYPE,
                mimeTypesMap.getContentType(file.getPath()));
    }
}

运行结果:

 Netty HTTP+XML协议栈开发

HttpXmlClient

Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {

                            //负责将二进制码流解码成HTTP应答消息
                            ch.pipeline().addLast("http-decoder",
                                    new HttpResponseDecoder());
                            //将一个HTTP请求的多个部分合并成一个完成的HTTP消息
                            ch.pipeline().addLast("http-aggregator",
                                    new HttpObjectAggregator(65536));
                            // XML响应解码器,解码服务端的响应消息
                            ch.pipeline().addLast(
                                    "xml-decoder",
                                    new HttpXmlResponseDecoder(Order.class,
                                            true));

                            //编码的时候按照从后往前的顺序调度进行
                            ch.pipeline().addLast("http-encoder",
                                    new HttpRequestEncoder());
                            // XML请求编码器,将客户端消息编码
                            ch.pipeline().addLast("xml-encoder",
                                    new HttpXmlRequestEncoder());
                            //添加业务逻辑编排类
                            ch.pipeline().addLast("xmlClientHandler",
                                    new HttpXmlClientHandle());
                        }
                    });

客户端处理器HttpXmlClientHandle:

public class HttpXmlClientHandle extends
        SimpleChannelInboundHandler<HttpXmlResponse> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //构造HttpXmlRequest对象
        HttpXmlRequest request = new HttpXmlRequest(null,
                OrderFactory.create(123));
        //发送HttpXmlRequest
        ctx.writeAndFlush(request);
    }

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

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                   HttpXmlResponse msg) throws Exception {
        //接收已经自动解码后的HttpXmlResponse对象
        System.out.println("The client receive response of http header is : "
                + msg.getHttpResponse().headers().names());
        System.out.println("The client receive response of http body is : "
                + msg.getResult());
    }
}
HttpXmlServer

HttpXmlServerHandler

1、接收客户端的信息

2、处理业务逻辑

3、发送响应给客户端

public class HttpXmlServerHandler extends
        SimpleChannelInboundHandler<HttpXmlRequest> {

    @Override
    public void channelRead0(final ChannelHandlerContext ctx,
                                HttpXmlRequest xmlRequest) throws Exception {
        //获取到已经解码的HttpXmlRequest
        HttpRequest request = xmlRequest.getRequest();
        //获取请求消息对象,将其打印出来
        Order order = (Order) xmlRequest.getBody();
        System.out.println("Http server receive request : " + order);
        //对Order请求消息进行业务逻辑编排
        dobusiness(order);
        //发送应答消息,发送成功后关闭链路
        ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null,
                order));
        if (!isKeepAlive(request)) {
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    ctx.close();
                }
            });
        }
    }

    private void dobusiness(Order order) {
        order.getCustomer().setFirstName("狄");
        order.getCustomer().setLastName("仁杰");
        List<String> midNames = new ArrayList<String>();
        midNames.add("李元芳");
        order.getCustomer().setMiddleNames(midNames);
        Address address = order.getBillTo();
        address.setCity("洛阳");
        address.setCountry("大唐");
        address.setState("河南道");
        address.setPostCode("123456");
        order.setBillTo(address);
        order.setShipTo(address);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        //在发生异常并且链路没有关闭的情况下,构造内部异常消息发送给客户端,发送完成后关闭链路
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }

    private static void sendError(ChannelHandlerContext ctx,
                                  HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                status, Unpooled.copiedBuffer("失败: " + status.toString()
                + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}

遗留的问题:

客户端处理器中的channelRead0方法,始终没能运行到,无法输出服务端的响应消息。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值