目录

一、需要的包

二、代码

三、导出jar包

四、启动jar包

五、使用


一、需要的包

二、代码


package com.cxf.http;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;public class NettyHttpServer{private int inetPort;public NettyHttpServer(int inetPort) {this.inetPort = inetPort;}public int getInetPort() {return inetPort;}public void init() throws Exception {EventLoopGroup parentGroup = new NioEventLoopGroup();EventLoopGroup childGroup = new NioEventLoopGroup();try {ServerBootstrap server = new ServerBootstrap();// 1. 绑定两个线程组分别用来处理客户端通道的accept和读写时间server.group(parentGroup, childGroup)// 2. 绑定服务端通道NioServerSocketChannel.channel(NioServerSocketChannel.class)// 3. 给读写事件的线程通道绑定handler去真正处理读写// ChannelInitializer初始化通道SocketChannel.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {// 请求解码器socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());// 将HTTP消息的多个部分合成一条完整的HTTP消息socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));// 响应转码器socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());// 解决大码流的问题,ChunkedWriteHandler:向客户端发送HTML5文件socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());// 自定义处理handlersocketChannel.pipeline().addLast("http-server", new NettyHttpServerHandler());}});System.out.println("Netty-http服务器已启动,端口" + inetPort);// 4. 监听端口(服务器host和port端口),同步返回// ChannelFuture future = server.bind(inetHost, this.inetPort).sync();ChannelFuture future = server.bind(this.inetPort).sync();// 当通道关闭时继续向后执行,这是一个阻塞方法future.channel().closeFuture().sync();} finally {childGroup.shutdownGracefully();parentGroup.shutdownGracefully();}}public static void main(String[] args) {NettyHttpServer nettyHttpServer = new NettyHttpServer(Integer.parseInt(args[0]));try {nettyHttpServer.init();} catch (Exception e) {e.printStackTrace();}}}
package com.cxf.http;import static io.netty.buffer.Unpooled.copiedBuffer;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;/*
* 自定义处理的handler
*/
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {/** 处理请求*/@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws IOException {FullHttpResponse response = null;if (fullHttpRequest.method() == HttpMethod.GET) {String data = getResponse(channelHandlerContext, fullHttpRequest);ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);response = responseOK(HttpResponseStatus.OK, buf);} else if (fullHttpRequest.method() == HttpMethod.POST) {String data = getResponse(channelHandlerContext, fullHttpRequest);ByteBuf content = copiedBuffer(data, CharsetUtil.UTF_8);response = responseOK(HttpResponseStatus.OK, content);} else {String data = "未找到对应的url";ByteBuf content = copiedBuffer(data, CharsetUtil.UTF_8);response = responseOK(HttpResponseStatus.INTERNAL_SERVER_ERROR, content);}// 发送响应channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);}private String getResponse(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws IOException {System.out.println("===============================");String uri = fullHttpRequest.getUri();System.out.println("请求url:" + uri);String content = fullHttpRequest.content().toString(CharsetUtil.UTF_8);System.out.println("请求内容:" + content);String path = new File(".").getCanonicalPath() + "/files" + uri;System.out.println("读取挡板文件路径:" + path);String data = getFileContent(path);System.out.println("返回内容:" + data);System.out.println("===============================");return data;
}
/*** @param fullHttpRequest* @return 获取参数*/private String getParam(FullHttpRequest fullHttpRequest) {ByteBuf content = fullHttpRequest.content();byte[] reqContent = new byte[content.readableBytes()];content.readBytes(reqContent);String strContent = "";try {strContent = new String(reqContent, "UTF-8");} catch (UnsupportedEncodingException e) {// TODO 自动生成的 catch 块e.printStackTrace();}return strContent;}/** 获取GET方式传递的参数*/private Map<String, Object> getGetParamsFromChannel(FullHttpRequest fullHttpRequest) {Map<String, Object> params = new HashMap<String, Object>();//if (fullHttpRequest.method() == HttpMethod.GET) {// 处理get请求QueryStringDecoder decoder = new QueryStringDecoder(fullHttpRequest.uri());Map<String, List<String>> paramList = decoder.parameters();for (Map.Entry<String, List<String>> entry : paramList.entrySet()) {params.put(entry.getKey(), entry.getValue().get(0));}return params;//} else {//    return null;//}}/** 获取POST方式传递的参数*/private Map<String, Object> getPostParamsFromChannel(FullHttpRequest fullHttpRequest) {Map<String, Object> params = new HashMap<String, Object>();if (fullHttpRequest.method() == HttpMethod.POST) {// 处理POST请求String strContentType = fullHttpRequest.headers().get("Content-Type").trim();if (strContentType.contains("x-www-form-urlencoded")) {params  = getFormParams(fullHttpRequest);} else if (strContentType.contains("application/json")) {try {params = getJSONParams(fullHttpRequest);} catch (UnsupportedEncodingException e) {return null;}} else {return null;}return params;} else {return null;}}/** 解析from表单数据(Content-Type = x-www-form-urlencoded)*/private Map<String, Object> getFormParams(FullHttpRequest fullHttpRequest) {Map<String, Object> params = new HashMap<String, Object>();HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpRequest);List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();for (InterfaceHttpData data : postData) {if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {MemoryAttribute attribute = (MemoryAttribute) data;params.put(attribute.getName(), attribute.getValue());}}return params;}/** 解析json数据(Content-Type = application/json)*/private Map<String, Object> getJSONParams(FullHttpRequest fullHttpRequest) throws UnsupportedEncodingException {Map<String, Object> params = new HashMap<String, Object>();ByteBuf content = fullHttpRequest.content();byte[] reqContent = new byte[content.readableBytes()];content.readBytes(reqContent);String strContent = new String(reqContent, "UTF-8");/*  JSONObject jsonParams = JSONObject.fromObject(strContent);for (Object key : jsonParams.keySet()) {params.put(key.toString(), jsonParams.get(key));}*/return params;}private FullHttpResponse responseOK(HttpResponseStatus status, ByteBuf content) {FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);if (content != null) {response.headers().set("Content-Type", "text/json;charset=UTF-8");response.headers().set("Content_Length", response.content().readableBytes());}return response;}/*** 读取文件的内容* 读取指定文件的内容* @param path 为要读取文件的绝对路径* @return 以行读取文件后的内容。* @since  1.0*/public static final String getFileContent(String path) throws IOException{String filecontent = "";try {File f = new File(path);if (f.exists()) {FileReader fr = new FileReader(path);BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为brString line = br.readLine(); //从文件读取一行字符串//判断读取到的字符串是否不为空while (line != null) {filecontent += line + "\n";line = br.readLine(); //从文件中继续读取一行数据}br.close(); //关闭BufferedReader对象fr.close(); //关闭文件}}catch (IOException e) {throw e;}return filecontent;}}

三、导出jar包

详细百度

四、启动jar包

五、使用

1、在jar包同级目录下创建files目录。

2、在files目录下新建test文件。

3、test文件中内容:

{"name":"zhangsan"}

4、使用postman发送测试一下吧。

5、url与文件对应规则

localhost:8083/test 后面的test就是files目录下对应的文件,文件内容会作为返回内容进行返回。

使用netty实现一个http挡板,轻量又实用。收藏起来吧相关推荐

  1. .NET Core 3.0 一个 jwt 的轻量角色/用户、单个API控制的授权认证库

    作者:痴者工良(朋友合作原创) 来源: https://www.cnblogs.com/whuanle/p/11743406.html 目录 说明 一.定义角色.API.用户 二.添加自定义事件 三. ...

  2. multipass基础入门,搭建本地迷你云,一个比VMware轻量的虚拟机软件

    介绍 multipass是一款轻量,且开源的虚拟机. Multipass是一个灵活.强大的工具,可用于多种用途.在其最简单的形式下,它可以用来在任何主机上快速创建和销毁Ubuntu虚拟机(实例).在更 ...

  3. 推荐一个简单、轻量、功能非常强大的C#/ASP.NET定时任务执行管理器组件–FluentScheduler...

    在C#WINFORM或者是ASP.NET的WEB应用程序中,根据各种定时任务的需求,比如:每天的数据统计,每小时刷新系统缓存等等,这个时候我们得应用到定时器这个东东. .NET Framework有自 ...

  4. 非常轻量又实用的鼠标拾色器小工具

    效果 下载 链接:https://download.csdn.net/download/qq_39706570/14502332 使用教程 第一步:双击打开软件: 第二步:设置电脑屏幕的缩放与布局为1 ...

  5. MDClub一个漂亮轻量的开源论坛系统

    简介: MDClub 是一个漂亮.轻量的开源论坛系统.运行在 PHP .MySQL 之上. 为了让它更轻量好用,造了不少轮子.富文本编辑器.UI 框架. 类 jQuery 的 DOM 操作库,全部自主 ...

  6. 轻量应用服务器MySQL远程连接踩坑

    不算是给阿里云打广告吧,因为被阿里云的"云服务器ECS" 和 "轻量应用服务器"搞的很蛋疼.很多年前,阿里云的学生机"云翼计划"默认就只有& ...

  7. 轻云服务器的性能,腾讯云轻量应用服务器性能评测(以香港地域为例)

    腾讯云轻量应用服务器香港节点24元/月,价格很不错,ForeignServer来说说腾讯云轻量服务器香港地域性能评测,包括腾讯云轻量应用服务器CPU型号配置.网络延迟速度测试: 腾讯云香港轻量应用服务 ...

  8. 13、腾讯云轻量应用服务器挂载文件系统

    前言:腾讯云轻量应用服务器+腾讯云文件存储(Cloud File Storage,CFS)系统的使用小记 轻量应用服务器系统版本是windows server 2012r 一.必要概念 1.1 轻量应 ...

  9. 【项目实战】阿里云轻量云服务器中安装JDK1.8

    一.背景 刚买了一个阿里云轻量云服务器,非常兴奋,第一件事肯定时,安装JDK1.8啦! 二.操作汇总 以下是在阿里云轻量云服务器中具体的操作 cd opt # (切换到opt目录中) mkdir ja ...

最新文章

  1. python正确方法,方法 - 廖雪峰的官方网站
  2. 机器学习奠基人Michael Jordan:下代技术是融合经济学,解读2项重要进展
  3. iOS很重要的 block回调
  4. c语言坐标三角形判断,【C语言】判断三角形类型(示例代码)
  5. 卓京计算机学校,卓京--计算机数据原理课程设计任务书.doc
  6. Swift中为什么输入“..”报错
  7. 项目NABCD的分析
  8. html span标签 不换行(有时span带中文时候是可以自动换行的)
  9. linux lamp实验报告,新手学Linux--构建lamp
  10. 楼市信贷新政力度超市场预期 房企放风要涨价
  11. jquery 之for 循环
  12. Pytorch——神经网络工具箱nn
  13. 极客大学产品经理训练营:需求评审 第13课总结
  14. session和cookie的内部原理
  15. krohne流量计接线图_电磁流量计如何接线_电磁流量计接线实物图
  16. 根据区的code获取省市的code代码,下面有切割数字方法
  17. 树莓派中怎么更新python_树莓派升级python的具体步骤
  18. 通达OA11.6复现
  19. python运算符讲解
  20. 印象笔记android,印象笔记(Evernote) Android SDK 更新

热门文章

  1. 架构师养成之道-02-jvm原理
  2. 尚硅谷SpringCloud(H版alibaba)框架开发教程(大牛讲授spring cloud) 最详细的。
  3. 异常信息配置文件已被另一个程序更改_抢先目睹:SpringBoot2.4配置文件加载机制大变化
  4. DC-DC电源PCB设计指南
  5. java自定义返回码_java – 自定义HTTP状态代码
  6. python自定义包_详解python自定义模块、包
  7. python 地理信息_GitHub - sujeek/geospatial-data-analysis-cn: Python地理信息数据教程中文版(GeoPandas、GIS)...
  8. java中的socket算法_GitHub - xiaohuiduan/pbft: pbft算法基于Socket的java实现
  9. Qt 中使用QPainter时,实现坐标变化的方法
  10. 在c++使用文件流(初学者必看)