netty可以作為http的服務器,處理客戶端的請求和響應,但是netty并沒有遵循servlet規(guī)范,和我們平時使用的web層框架struts2、springmvc等框架底層是有所區(qū)別的。netty構(gòu)建的服務不需要部署在像tomcat容器中,可以單獨使用。netty是一個底層的技術(shù)框架,對于請求路由沒有提供任何的支持。
maven依賴
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.16.Final</version>
</dependency>
http服務端
public class TestServer {
public static void main(String[] args) throws InterruptedException {
//定義兩個基于NIO的事件循環(huán)組,死循環(huán),不斷的接收客戶端的連接
//bossGroup:不斷的從客戶端接收連接,但是不對連接做任何處理,轉(zhuǎn)給workGroup
//workGroup:對連接進行真正的處理
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
//服務端啟動類,對啟動做了一定的封裝
ServerBootstrap serverBootstrap = new ServerBootstrap();
//NioServerSocketChannel 反射方式創(chuàng)建
serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
ChannelInitializer
作用:用于在某個Channel注冊到EventLoop后,對這個Channel執(zhí)行一些初始化操作。ChannelInitializer雖然會在一開始會被注冊到Channel相關(guān)的pipeline里,但是在初始化完成之后,ChannelInitializer會將自己從pipeline中移除,不會影響后續(xù)的操作。
//服務端的初始化器
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
//連接一旦被注冊之后就會被創(chuàng)建,執(zhí)行initChannel回調(diào)的方法
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//管道
ChannelPipeline pipeline = ch.pipeline();
//HttpServerCodec TestHttpServerHandler 多實例對象
pipeline.addLast("httpServerCodec",new HttpServerCodec());
pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
}
}
自定義處理器,里面是服務器端的處理邏輯
//自定義處理器
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
//讀取客戶端的請求并向客戶端返回響應的方法
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
ByteBuf content = Unpooled.copiedBuffer("Hello World",CharsetUtil.UTF_8);
//http響應
FullHttpResponse 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());
//返回客戶端
ctx.writeAndFlush(response);
}
}
測試
啟動服務端,瀏覽器輸入:http://localhost:8888,可以看見返回 hello world .

image.png