一、环境搭建
创建工程,引入Netty依赖
二、基于Netty的请求响应Demo
1、TestHttpServerHandle 处理器。读取客户端发送过来的请求,并且向客户端返回hello world响应
package com.example.firstexample; 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; public class TestHttpServerHandle extends SimpleChannelInboundHandler<HttpObject>{ //读取客户端发送过来的请求,并且向客户端返回响应 protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception { if(httpObject instanceof HttpRequest){ ByteBuf content = Unpooled.copiedBuffer("Hello world", CharsetUtil.UTF_8); 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()); //写回客户端 channelHandlerContext.writeAndFlush(response); } } }
2、TestServerInitializer 类
public class TestServerInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("httpServerCode", new HttpServerCodec()); pipeline.addLast("testHttpServerHandler", new TestHttpServerHandle()); } }
3、TestServer 类
package com.example.firstexample; 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 TestServer { public static void main(String[] args) throws Exception { //bossGroup获取连接 EventLoopGroup bossGroup = new NioEventLoopGroup(); //workerGroup处理连接 EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap serverBootstrap = new ServerBootstrap(); //1、启动Bootstrap服务器,服务器关联两个事件循环组bossGroup,workerGroup //2、并且关联事件处理器,处理器使用TestServerInitializer定义,如TestServerInitializer里使用了处理器TestHttpServerHandle serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new TestServerInitializer()); ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
启动main方法
4、测试
5、总结Netty执行流程
1)启动Bootstrap服务器,服务器关联两个事件循环组bossGroup(获取连接),workerGroup(处理连接)
2)并且关联事件处理器,处理器使用TestServerInitializer定义,如TestServerInitializer里使用了处理器TestHttpServerHandle
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!