Netty is an asynchronous communication framework based on the JAVA NIO class library, which features asynchronous non-blocking, event-driven, high performance, high reliability, and high customization. In other words, Netty is a NIO framework that can be used to quickly and easily develop Web applications such as client and server protocols. Netty greatly simplifies the development of network programs such as the development of TCP and UDP sockets. Netty has gradually become the preferred framework for Java NIO programming, and in Netty, when the two sides of the communication establish a connection, the data is transferred in Bytebuf way. Therefore, when we build the HTTP server, we use Httprequestdecoder to process the BYTEBUF data stream and convert it to an HTTP object. The code is as follows:
Maven Dependency
<dependency> <groupId>io.netty</groupId> <artifactid>netty-all</artifactid > <version>4.1.0.Final</version> </dependency>
Httpserver class
PackageCom.example.demo.netty;ImportIo.netty.bootstrap.ServerBootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioServerSocketChannel;ImportIo.netty.handler.codec.http.HttpServerCodec; Public classHttpserver { Public Static voidMain (string[] args)throwsinterruptedexception {eventloopgroup bossgroup=NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try{Serverbootstrap b=NewServerbootstrap (); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Childhandler (NewChannelinitializer<socketchannel>() {@Override Public voidInitchannel (Socketchannel ch)throwsException {Channelpipeline pipeline=Ch.pipeline (); Pipeline.addlast (NewHttpservercodec ()); Pipeline.addlast (NewHttpserverhandler ()); } }); Channelfuture F= B.bind (8080). sync (); F.channel (). Closefuture (). sync (); } finally{workergroup.shutdowngracefully (); Bossgroup.shutdowngracefully (); } }}
Httpserverhandler class
PackageCom.example.demo.netty;Importjava.io.UnsupportedEncodingException;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInboundHandlerAdapter;ImportIo.netty.handler.codec.http.DefaultFullHttpResponse;ImportIo.netty.handler.codec.http.FullHttpResponse;Importio.netty.handler.codec.http.HttpRequest;ImportIo.netty.handler.codec.http.HttpResponseStatus;Importio.netty.handler.codec.http.HttpVersion;ImportIo.netty.handler.codec.http.QueryStringDecoder;classHttpserverhandlerextendsChannelinboundhandleradapter {@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsunsupportedencodingexception {if(msginstanceofHttpRequest) { //request, the decoder translates the request into a HttpRequest objectHttpRequest request =(HttpRequest) msg; //GET Request ParametersQuerystringdecoder Querystringdecoder =NewQuerystringdecoder (Request.uri ()); String name= "Netty"; if(Querystringdecoder.parameters (). Get ("name")! =NULL) {Name= Querystringdecoder.parameters (). Get ("name"). Get (0); } //Response HTMLString responsehtml = "; byte[] responsebytes = Responsehtml.getbytes ("UTF-8"); intContentLength =responsebytes.length; //constructs a Fullhttpresponse object, Fullhttpresponse contains the message bodyFullhttpresponse response =Newdefaultfullhttpresponse (httpversion.http_1_1, Httpresponsestatus.ok, Unpooled.wrappedbuffer (responseBytes)); Response.headers (). Set ("Content-type", "text/html; Charset=utf-8 "); Response.headers (). Set ("Content-length", Integer.tostring (contentlength)); Ctx.writeandflush (response); }} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) {cause.printstacktrace (); Ctx.close (); }}
Run Httpserver in the Main method, start Httpserver, open the browser input Http://localhost:8080?name=zhangsan, the results are as follows:
Netty Building an HTTP server