package io.netty.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class HttpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup boosGroup = new NioEventLoopGroup(1);
//真正与客户端数据打交道
EventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup,workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new HttpServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();
channelFuture.channel().closeFuture().sync();
}finally {
//优雅的关闭
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package io.netty.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
/**
* SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter 子类
* HttpObject 表示 客户端和服务器端 相互通信的数据 被封装成HttpObject
*/
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
/**
* 读取客户端数据
* @param channelHandlerContext
* @param httpObject
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
//判断msg 是否是HttpRequest
if(httpObject instanceof HttpRequest){
//获取HttpRequest
HttpRequest httpRequest=(HttpRequest)httpObject;
URI uri = new URI(httpRequest.uri());
if("/favicon.ico".equals(uri.getPath())){
System.out.println("请求了favicon.ico 不做处理");
return;
}
System.out.println("httpObject 类型"+ httpObject.getClass());
System.out.println("客户端地址"+ channelHandlerContext.channel().remoteAddress());
//回复信息给浏览器
ByteBuf content= Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
//构造一个http的响应
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
//构建好的response返回
channelHandlerContext.writeAndFlush(response);
}
}
}
package io.netty.http;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//先获取管道
ChannelPipeline pipeline = socketChannel.pipeline();
//httpServerCodec netty提供的对http的编解码器
pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
pipeline.addLast("MyHttpServerHandler",new HttpServerHandler());
}
}