Author: rickiyang reference: www.cnblogs.com/rickiyang/p…

In this section we are going to look at Netty. Before we use Netty, we are going to learn what Netty can do.

1. What can I do with Netty

  1. Develop asynchronous, non-blocking TCP network applications;
  2. Develop asynchronous, non-blocking UDP network applications;
  3. Develop asynchronous file transfer applications;
  4. Develop asynchronous HTTP server and client applications;
  5. Provides integration with various codec frameworks, including Google Protobuf, Jboss Marshalling, Java serialization, compression codec, XML codec, string codec, etc. These codec frameworks can be directly used by users;
  6. Provide a variety of forms of basic codec libraries, which can be very convenient to realize the second customization and development of private protocol stack codec framework;
  7. Based on the pipeline-handler mechanism of responsibility chain mode, users can intercept and customize network events very conveniently.
  8. All I/O operations are asynchronous. Users can use the Future-Listener mechanism to Get the result or Notify the result after the I/O thread completes the operation. The user’s service thread does not need to wait for the result synchronously.
  9. IP whitelist control;
  10. Print message code stream;
  11. Flow control and shaping;
  12. Performance statistics;
  13. Heartbeat detection based on link idle event detection

2. Netty common classes

Here we’re going to go through some of the classes that we use a lot, and then we’re going to get a sense of what each line is about when we write our introductory program.

EventLoop,EventLoopGroup

The purpose of an EventLoop is to handle IO operations for a Channel. An EventLoop can serve multiple channels. An EventLoop group contains multiple Eventloops.

BootStrap,ServerBootstrap

A Netty application usually starts with a Bootstrap, which is used to configure the entire Netty program and connect various components together.

ChannelInitializer

When a link is created, we need to know how to receive and send data. Of course, we have various Handler implementations to handle it. ChannelInitializer is used to configure these handlers. And add handlers to ChannelPipeline.

Handler

To support various protocols and ways of handling data, the Handler component was born. Handler is used to handle a wide range of events, such as connections, data receiving, exceptions, data conversion, etc.

ChannelInboundHandler

One of the most commonly used handlers. The ChannelInboundHandler is used to handle the events that occur when data is received. In other words, the ChannelInboundHandler is used to handle the core business logic.

Future

In Netty all IO operations are asynchronous, so you can’t immediately know if the message was handled correctly or not, but you can wait for it to complete or register a listener. This is done with Future and ChannelFutures, where they can register a listener. Listening is automatically triggered when the operation succeeds or fails. In short, all operations return a ChannelFuture.

3. First Helloworld

We’ve covered the common classes above, so let’s use them to build our first application. For this example, I’m using Maven to build the project. Skip the first step if you’re using a normal project.

Maven jar:

<dependency> <groupId> io.ty </groupId> <artifactId>netty-all</artifactId> <version>4.1.5.Final</version> </dependency>Copy the code

Let’s write the client side:

public class HelloWorldClient { private int port; private String address; public HelloWorldClient(int port,String address) { this.port = port; this.address = address; } public void start(){ EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ClientChannelInitializer()); try { Channel channel = bootstrap.connect(address,port).sync().channel(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); for(;;) { String msg = reader.readLine(); if(msg == null){ continue; } channel.writeAndFlush(msg + "\r\n"); } } catch (Exception e) { e.printStackTrace(); }finally { group.shutdownGracefully(); }} public static void main(String[] args) {HelloWorldClient client = new HelloWorldClient(7788,"127.0.0.1"); client.start(); }}Copy the code

ChannelInitializer is used to configure the handler for handling data:

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); /* * this place must correspond to the server. Otherwise, decoding and encoding will not work properly. * * Decoding and encoding will be explained in detail in the next section. * * / pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); // our own handler pipeline.addlast ("handler", new HelloWorldClientHandler()); }}Copy the code

Write our own handler to handle the data in our own way:

public class HelloWorldClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server say : "+msg.toString()); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client is active"); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client is close"); }}Copy the code

Now that we’re done with the client side, let’s start with the server side:

public class HelloWordServer { private int port; public HelloWordServer(int port) { this.port = port; } public void start(){ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap server = new ServerBootstrap().group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ServerChannelInitializer()); try { ChannelFuture future = server.bind(port).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); }finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } public static void main(String[] args) { HelloWordServer server = new HelloWordServer(7788); server.start(); }}Copy the code

ChannelInitializer for server:

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); Pipeline. AddLast ("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); // own logical Handler pipeline.addlast (" Handler ", new HelloWordServerHandler()); }}Copy the code

Server-side handler:

public class HelloWordServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(ctx.channel().remoteAddress()+"===>server: "+msg.toString()); ctx.write("received your msg"); ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); ctx.close(); }}Copy the code

The above server side and client side of the code have been written, let’s start the server side, and then start the client side, I am in the client side let manual input, input after the end of the press enter, the server side can accept the data.

Client:

Server:

Recent hot articles recommended:

1.1,000+ Java Interview Questions and Answers (2021)

2. I finally got the IntelliJ IDEA activation code thanks to the open source project. How sweet!

3. Ali Mock is officially open source, killing all Mock tools on the market!

4.Spring Cloud 2020.0.0 is officially released, a new and disruptive version!

5. “Java Development Manual (Songshan version)” the latest release, quick download!

Feel good, don’t forget to click on + forward oh!