What is Netty
References: Time Geeks Fu Jian teacher "Netty source code analysis and practical" Talk is cheap.show me the code!
Official website ( https://netty.io/ ) indicates that: "Netty is an asynchronous event- driven network application framework for rapid development of maintainable high performance protocol servers & clients.", Translates to: Netty is an asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients. Simple split can be understood:
① nature: web application framework
② implementation: asynchronous, event-driven
③ characteristics: high performance, maintenance, rapid development
④ purposes: to develop server and client
This is the official website of a structure to chart:
Nettty difficult to see a total of three parts, the bottom layer is the core, from the bottom up, the bottom is "zero copy Buffer", a grid is up "the API communication layer", and then the grid is a "expansion the event model ", top left is the transport layer services, including the Http Tunnel, TCP's Socket, UDP Datagram so on the upper right is Netty support a variety of protocols, such as we often say that the HTTP protocol, WebSocket protocol, Google's ProtoBuf agreement and so on.
The first HelloWorld
Build a project with Maven InterlliJ IDEA, Netty added in pom.xml configuration file dependency
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.10.Final</version> </dependency>
Server-side MyService.java
package com.lql.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author: lql * @date: 2019.10.14 * Description: 第一个Netty程序 服务器 */ public class MyServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap sb = new ServerBootstrap(); sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new MyServerHandler()); } }); ChannelFuture f = sb.bind(8090).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
Write MyServerHandler.java
package com.lql.netty; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * @author: lql * @date: 2019.10.14 * Description: */ @Sharable public class MyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
Again write a client MyClient.java
package com.lql.netty; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author: lql * @date: 2019.10.14 * Description: 第一个Netty程序 客户端 */ public class MyClient { public static void main(String[] args) throws Exception { //客户端只需要一个事件循环组 EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p =socketChannel.pipeline (); p.addLast ( new new LoggingHandler (LogLevel.INFO)); p.addLast ( new new MyClientHandle ()); } }); // start client ChannelFuture f = b.connect ( "127.0.0.1" , 8090 ) .sync (); // wait for the connection is closed f.channel () closeFuture () Sync ();.. } the finally { // elegant closed group.shutdownGracefully (); } } }
Similarly, create MyClientHandle.java
package com.lql.netty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.concurrent.TimeUnit; /** * @author: lql * @date: 2019.10.14 * Description: */ public class MyClientHandle extends ChannelInboundHandlerAdapter{ private final ByteBuf firstMessage; public MyClientHandle() { firstMessage = Unpooled.wrappedBuffer("I am echo message".getBytes()); } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(firstMessage); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException { TimeUnit.SECONDS.sleep(3); ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
Start the server, start the client, the result is feasible!
Netty and Spring mvc also be the same. As follows:
Establish HttpServer.java
package com.lql.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpServerExpectContinueHandler; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author: lql * @date: 2019.10.14 * Description: * Created with IntelliJ IDEA */ public class HttpServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer() { protected void initChannel(Channel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); p.addLast(new HttpServerExpectContinueHandler()); p.addLast(new HttpServerHandler()); } }); ChannelFuture channelFuture = b.bind(8899).sync(); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
Re-establish HttpServerHandler.java
package com.lql.netty; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; /** * @author: lql * @date: 2019.10.14 * Description: * Created with IntelliJ IDEA */ public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> { private static final byte[] CONTENT = "helloworld".getBytes(); @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT)); response.headers() .set(HttpHeaderNames.CONTENT_TYPE, "text/plain") .setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
Start HttpServer: URL input " HTTP: // localhost: 8899 / ", shown below:
At this point, Netty's HelloWorld has finished!