目录
HTTP协议简介
Http协议是基于TCP/IP协议基础上用于超文本传输的应用层协议,主要有以下特点:
- 支持C/S模式
- 无状态
- 灵活
- 简单,直接在browser中指定url,携带请求参数或请求消息体就可与服务器通信
Http请求消息
HTTP请求报文由3部分组成(请求行+请求头+请求体)
Http响应消息
HTTP的响应报文也由三部分组成(响应行+响应头+响应体):
Http服务器实现
HttpServerCodec是对http消息编码和解码,相当于:HttpRequestDecoder和HttpResponseEncoder。因此在pipline.addLast时要么开始就添加一个HttpServerCodec,或HttpRequestDecoder和HttpResponseEncoder分开添加。
public class HttpServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGoup = new NioEventLoopGroup(8);
try{
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
.group(bossGroup, workGoup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// HttpServerCodec 是 netty 提供的处理 http 的 编-解码器
pipeline.addLast("httpServerCodec", new HttpServerCodec());
// 增加一个自定义的 handler
pipeline.addLast("MyHttpServerHandler", new MyHttpServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(7777).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workGoup.shutdownGracefully();
}
}
}
业务处理器
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest){
System.out.println("pipeline hashcode" + ctx.pipeline().hashCode() + " myHttpServerHandler hash=" + this.hashCode());
System.out.println("msg 类型:" + msg.getClass());
System.out.println("客户端地址:" + ctx.channel().remoteAddress());
HttpRequest httpRequest = (HttpRequest) msg;
String uri = httpRequest.uri();
System.out.println("uri" + uri);
URI httpUri = new URI(uri);
// 处理请求
if ("/list".equals(httpUri.getPath())){
System.out.println("调用list接口");
return ;
}
if ("/add".equals(httpUri.getPath())){
System.out.println("调用add接口");
return ;
}
ByteBuf content = Unpooled.copiedBuffer("对不起, 资源没有找到!", CharsetUtil.UTF_8);
// 构建一个响应
DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
ctx.writeAndFlush(httpResponse);
}
}
}
使用浏览器进行访问:
案例
静态服务服务器