失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > netty4搭建简单的http服务器

netty4搭建简单的http服务器

时间:2021-10-19 00:34:29

相关推荐

netty4搭建简单的http服务器

话不多说上代码

import ty.bootstrap.ServerBootstrap;import ty.channel.ChannelFuture;import ty.channel.ChannelInitializer;import ty.channel.EventLoopGroup;import ty.channel.nio.NioEventLoopGroup;import ty.channel.socket.SocketChannel;import ty.channel.socket.nio.NioServerSocketChannel;import ty.handler.codec.http.HttpObjectAggregator;import ty.handler.codec.http.HttpRequestDecoder;import ty.handler.codec.http.HttpResponseEncoder;import ty.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服务器已启动");// 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(8080);try {nettyHttpServer.init();} catch (Exception e) {e.printStackTrace();}}}

import ty.buffer.ByteBuf;import ty.channel.ChannelFutureListener;import ty.channel.ChannelHandlerContext;import ty.channel.SimpleChannelInboundHandler;import ty.handler.codec.http.*;import ty.handler.codec.http.multipart.DefaultHttpDataFactory;import ty.handler.codec.http.multipart.HttpPostRequestDecoder;import ty.handler.codec.http.multipart.InterfaceHttpData;import ty.handler.codec.http.multipart.MemoryAttribute;import ty.util.CharsetUtil;import java.io.UnsupportedEncodingException;import java.util.HashMap;import java.util.List;import java.util.Map;import static ty.buffer.Unpooled.copiedBuffer;/** 自定义处理的handler*/public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {/** 处理请求*/@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {FullHttpResponse response = null;if (fullHttpRequest.method() == HttpMethod.GET) {//get方式传递的参数System.out.println(""+getGetParamsFromChannel(fullHttpRequest));//返回信息String data = "GET method over";ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);response = responseOK(HttpResponseStatus.OK, buf);} else if (fullHttpRequest.method() == HttpMethod.POST) {String url=fullHttpRequest.getUri();String data = "这是post返回";if(url.endsWith("CXF")){try {//System.out.println("业务逻辑");} catch (Exception e) {// TODO 自动生成的 catch 块e.printStackTrace();}}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);}/*** @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/plain;charset=UTF-8");response.headers().set("Content_Length", response.content().readableBytes());}return response;}}

如果觉得《netty4搭建简单的http服务器》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。