什么是netty
Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架。
netty与tomcat
Netty和Tomcat最大的区别就在于通信协议,Tomcat是基于Http协议的,他的实质是一个基于http协议的web容器,但是Netty不一样,他能通过编程自定义各种协议,因为netty能够通过codec自己来编码/解码字节流,完成类似redis访问的功能,这就是netty和tomcat最大的不同。
netty 实现接收http请求及响应
NettyHttpServerHandler :实际处理的handler,可以处理 get 和 post 请求
package com.example.demo.httpserver.handler;
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.*;
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;
import net.sf.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.netty.buffer.Unpooled.copiedBuffer;
/*
* 自定义处理的handler
*/
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
/*
* 处理请求
*/
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
System.out.println(fullHttpRequest);
FullHttpResponse response = null;
if (fullHttpRequest.method() == HttpMethod.GET) {
System.out.println(getGetParamsFromChannel(fullHttpRequest));
String data = "GET method over";
ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);
response = responseOK(Http