2, the first example netty, simple http server

Netty server to start with a simple http request can be processed.

In accordance with previous procedures use netty written. Paste the code

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: main role is described supports http request to write a pseudo server. Can see the request header and the data may also be constructed own Response
 10    * @CreateDate: 23:08 2019/7/3
 . 11    * @Version: 1.0
 12 is   * / 
13 is  public  class{The TestServer
 14  
15      public  static  void main (String [] args) throws InterruptedException {
 16          EventLoopGroup bossGroup = new new NioEventLoopGroup (); // thread event loop for receiving a set of an infinite loop 
. 17          EventLoopGroup workerGroup = new new NioEventLoopGroup (); // thread for processing the event loop endless loop group 
18 is  
. 19          the try {
 20 is              // starter 
21 is              of ServerBootstrap ServerBootstrap = new new of ServerBootstrap ();
 22 is              serverBootstrap.group (bossGroup, workerGroup) //Add two provided thread group 
23 is                      .Channel (NioServerSocketChannel. Class )
 24                      .childHandler ( new new TestSereverInitlalizer ()); // this is provided to initialize the class 
25  
26 is              ChannelFuture ChannelFuture = serverBootstrap.bind (8899) .sync (); // blocked wait 
27  
28              channelFuture.channel () closeFuture () Sync ();..
 29          } the finally {
 30              bossGroup.shutdownGracefully (); // Close elegant
 31 is              workerGroup.shutdownGracefully ();
 32          }
 33 is  
34 is      }
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 new HttpServerCodec ()); // HTTP used in 
13 is          pipeline.addLast ( "testHttpSereverHandle", new new TestHttpServerHandler ()); // the handler previously set added to the last 
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 is          System.out.println (ctx.channel () of the remoteAddress ().);
 19  
20          IF (msg instanceof the HttpRequest) { // If you do not add this, when accessed using curl, being given access browser does not complain
 21  //             System.out.println ( "performed !!!!!") ; 
22 is  
23 is              the httpRequest httpRequest = (the httpRequest) MSG;
 24  
25              System.out.println ( "request method name" +. httpRequest.getMethod () name ());
 26 is  
27              the URI URI = new new the URI (httpRequest.uri ());
 28              IF ( "/favicon.ico" .equals (uri.getPath ())) {
 29                  the System.out .println ( "request the favicon.ico" );
 30                  return ;
 31 is              }
 32  
33 is              // returned content to the client 
34 is              ByteBuf Unpooled.copiedBuffer content = ( "the Hello World" , CharsetUtil.UTF_8);
 35              // Construction Response 
36              the Response = FullHttpResponse new 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 }

 

Guess you like

Origin www.cnblogs.com/amibandoufu/p/11442648.html