2、netty第一个例子,简单的http服务器
用netty来启动一个简单的可处理http请求的服务器。
依照前面写的使用netty的过程。贴上代码
server
1 import io.netty.bootstrap.ServerBootstrap; 2 import io.netty.channel.ChannelFuture; 3 import io.netty.channel.EventLoopGroup; 4 import io.netty.channel.nio.NioEventLoopGroup; 5 import io.netty.channel.socket.nio.NioServerSocketChannel; 6 7 /** 8 * @ClassName: TestServe 9 * @Description: 描述 主要作用是写一个可以支持 http 请求的伪服务器。可以看到请求的头和数据 ,也可以自己构建response 10 * @CreateDate: 2019/7/3 23:08 11 * @Version: 1.0 12 */ 13 public class TestServer { 14 15 public static void main(String[] args) throws InterruptedException { 16 EventLoopGroup bossGroup = new NioEventLoopGroup();//线程,用来接收 事件循环组 死循环 17 EventLoopGroup workerGroup = new NioEventLoopGroup();//线程,用来处理 事件循环组 死循环 18 19 try{ 20 //启动器 21 ServerBootstrap serverBootstrap = new ServerBootstrap(); 22 serverBootstrap.group(bossGroup, workerGroup)//添加设置两个线程组 23 .channel(NioServerSocketChannel.class) 24 .childHandler(new TestSereverInitlalizer());//这里去设置初始化类 25 26 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();//阻塞,等待 27 28 channelFuture.channel().closeFuture().sync(); 29 }finally { 30 bossGroup.shutdownGracefully();//优雅关闭 31 workerGroup.shutdownGracefully(); 32 } 33 34 } 35 }
Initlalizer
1 import io.netty.channel.ChannelInitializer; 2 import io.netty.channel.ChannelPipeline; 3 import io.netty.channel.socket.SocketChannel; 4 import io.netty.handler.codec.http.HttpServerCodec; 5 6 public class TestSereverInitlalizer extends ChannelInitializer<SocketChannel> { 7 8 @Override 9 protected void initChannel(SocketChannel ch) throws Exception { 10 ChannelPipeline pipeline = ch.pipeline(); 11 12 pipeline.addLast("httpServerCodec",new HttpServerCodec());//http里用的 13 pipeline.addLast("testHttpSereverHandle", new TestHttpServerHandler());//把前面设置的handler加到最后 14 15 } 16 }
Handler
1 import io.netty.buffer.ByteBuf; 2 import io.netty.buffer.Unpooled; 3 import io.netty.channel.ChannelHandlerContext; 4 import io.netty.channel.SimpleChannelInboundHandler; 5 import io.netty.handler.codec.http.*; 6 import io.netty.util.CharsetUtil; 7 8 import java.net.URI; 9 import java.net.URL; 10 11 public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> { 12 13 @Override 14 protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { 15 16 System.out.println(msg.getClass()); 17 18 System.out.println(ctx.channel().remoteAddress()); 19 20 if(msg instanceof HttpRequest) {//如果没加这个,用curl访问时,会报错,用浏览器访问不会报错 21 // System.out.println("执行了!!!!!"); 22 23 HttpRequest httpRequest = (HttpRequest) msg; 24 25 System.out.println("请求方法名" + httpRequest.getMethod().name()); 26 27 URI uri = new URI(httpRequest.uri()); 28 if("/favicon.ico".equals(uri.getPath())) { 29 System.out.println("请求 favicon.ico"); 30 return; 31 } 32 33 //向客户端返回的内容 34 ByteBuf content = Unpooled.copiedBuffer("Hello world", CharsetUtil.UTF_8); 35 //构建response 36 FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content); 37 response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); 38 response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); 39 40 ctx.writeAndFlush(response); 41 ctx.channel().close(); 42 } 43 44 } 45 46 @Override 47 public void channelActive(ChannelHandlerContext ctx) throws Exception { 48 System.out.println("channel active"); 49 super.channelActive(ctx); 50 } 51 52 @Override 53 public void channelInactive(ChannelHandlerContext ctx) throws Exception { 54 System.out.println("channel inactive"); 55 super.channelInactive(ctx); 56 } 57 58 @Override 59 public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 60 System.out.println("channel registered"); 61 super.channelRegistered(ctx); 62 } 63 64 @Override 65 public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 66 System.out.println("channel unregistered"); 67 super.channelUnregistered(ctx); 68 } 69 70 @Override 71 public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 72 System.out.println("handler added"); 73 super.handlerAdded(ctx); 74 } 75 }