1. 程式人生 > >Netty的http服務器編程(三)

Netty的http服務器編程(三)

socket mil sts 第一個 group eof pool nbsp last

Netty提供的handlerHttpServerCodec http 請求編解碼處理類

第一個netty的例子,,server服務端的編寫,客戶端使用 curl : http://IP:PORT請求

服務啟動類

 1 public class TestServer {
 2 
 3     public static void main(String[] args) throws Exception {
 4 
 5         //定義兩個線程組
 6         EventLoopGroup bossGroup = new NioEventLoopGroup();//接收連接,分發給worker
 7         EventLoopGroup workerGroup = new NioEventLoopGroup();//處理連接
 8 
 9         try{
10             //啟動服務器  : 簡化服務端啟動
11             ServerBootstrap serverBootstrap = new ServerBootstrap();
12             serverBootstrap.group(bossGroup,workerGroup)
13                     .channel(NioServerSocketChannel.class)
14                     .childHandler(new TestServerInitializer());//子處理器
15 
16             //綁定端口
17             ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
18             channelFuture.channel().closeFuture().sync();
19         }finally {
20 
21             //優雅關閉線程組
22             bossGroup.shutdownGracefully();
23             workerGroup.shutdownGracefully();
24         }
25 
26 
27 
28     }
29 
30 
31 }

初始化類 :

 1 public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
 2 
 3     @Override
 4     protected void initChannel(SocketChannel ch) throws Exception {
 5         //攔截器
 6         ChannelPipeline pipeline = ch.pipeline();
 7         //註冊攔截器
 8         pipeline.addLast("httpServerCodec",new HttpServerCodec());//請求編解碼
 9         pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
10     }
11 }

自定義處理器類:

 1 public class TestHttpServerHandler  extends SimpleChannelInboundHandler<HttpObject> {
 2 
 3     //讀取客戶端的請求,向客戶端返回響應的方法
 4     //計劃在5.0 改名 messagereceived  消息接收,5.0已廢棄
 5     @Override
 6     protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
 7 
 8         System.out.println(msg.getClass());
 9 
10         System.out.println(ctx.channel().remoteAddress());
11 
12         Thread.sleep(8000);
13 
14         if(msg instanceof HttpRequest){
15             HttpRequest httpRequest = (HttpRequest)msg;
16 
17             System.out.println("請求方法名:"+httpRequest.getMethod().name());
18 
19             URI uri = new URI(httpRequest.getUri());
20             if("/favicon.ico".equals(uri.getPath())){
21                 System.out.println("請求favicon.ico");
22                 return;
23             }
24             //構造響應內容
25             ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
26 
27             FullHttpResponse response = new DefaultFullHttpResponse(
28                     HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
29 
30             response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
31             response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
32 
33 
34             //返回響應
35             ctx.writeAndFlush(response);
36             ctx.close();
37         }
38 
39     }
40 
41     @Override
42     public void channelActive(ChannelHandlerContext ctx) throws Exception {
43         System.out.println("channel active");
44         super.channelActive(ctx);
45     }
46 
47     @Override
48     public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
49         System.out.println("channel registered");
50         super.channelRegistered(ctx);
51     }
52 
53     @Override
54     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
55         System.out.println("handler added");
56         super.handlerAdded(ctx);
57     }
58 
59     @Override
60     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
61         System.out.println("channel inactive");
62         super.channelInactive(ctx);
63     }
64 
65     @Override
66     public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
67         System.out.println("channel unregistered");
68         super.channelUnregistered(ctx);
69     }
70 }

Netty的http服務器編程(三)