Learn netty from scratch - the first netty program

what was said before

Before learning to use netty, I had many doubts. I will write down my doubts and answers first, hoping to help friends who have the same doubts.

Question : Choice of netty version, 3, 4, 5.
Answer : The changes of 3 and 4 are quite big, but the ones of 4 and 5 are not big. Now the official version is 4. Originally, there was 5, but it was removed from the shelves, but 5 can be found in many maven libraries. Everyone wants the life cycle of the content they learn to be longer, and they don’t want to discard it as soon as they finish learning. My recommended version is 4. Go with the official.
Question : Selection of netty's book
Answer : I have read a few books, and finally think "netty authoritative guide" is good, his knowledge points are relatively comprehensive, you may have a certain foundation to start reading, otherwise many people will be confused when reading the IO model Confused. This book is based on 5, and I still recommend it. The main 4 and 5 have not changed much. Changes are still acceptable.
Question : Do you have to be able to use java IO, NIO to learn netty?
Answer : As a framework, netty shields these complex operations, so there is no need to be particularly proficient in java, and netty provides its own wrapper class. If you are starting to learn this framework, I think it is not necessary, but the basic socket programming foundation is required. The main thing is to have a certain socket foundation, you can have a good logical thinking, or you don't know what the framework does. If you want to continue reading the source code later, you need to supplement all this knowledge. Question: Advantages of netty

start the program

Start with socket analysis

Everyone knows that socket transmission has nothing to do with language and machine (of course, the results read by big-endian machines and little-endian machines are different and require special processing, but all machines can receive). Therefore, our program does not write the client, and uses the telnet that comes with the system for client access. We only write the server side.

Server analysis

Anyone who has written a socket program knows that the socket of the server has several general operations, such as accept, read, and write. This time, we mainly focus on these for comparison.

	public void bind(int port) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap server = new ServerBootstrap();
			server.group(boss, worker).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<Channel>() {

						@Override
						protected void initChannel(Channel ch) throws Exception {

							ch.pipeline().addLast(new MessageHandler());
						}

					});

			ChannelFuture sync = server.bind(port).sync();
			sync.channel().closeFuture().sync();
		} catch (InterruptedException e) {

			e.printStackTrace();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}

	}

Why is the above code written in this way? I suggest that you write this first without considering this problem. As a server-side writer, we mainly care about the port. No matter what framework or model, sockets are mainly ports, and the only business we need to write is MessageHandler

public class MessageHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		ByteBuf buf =(ByteBuf)msg;
		int readableBytes = buf.readableBytes();
		byte[] bytes =new byte[readableBytes];
		buf.readBytes(bytes);
		
		System.out.println(new String(bytes));
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("connection");

	}
	

}

Here I recreated two methods, one is channelRead and the other is channelActive. It obviously corresponds to the accpet and read I mentioned above. Many people here ask why msg must be received by byte. This is actually related to the protocol, but I suggest that you first think about the ordinary socket programming, don't you get inputstream and outputstream, they themselves deal with byte streams. So it's the same here. Process byte streams.

use of telnet

When many people learn sockets, they write their own clients and their own servers. So let's talk about the use of telnet.

telnet ip port ctrl + ] Enter the command message mode send hello This will send hello

Use of frames

You can complete the program through the above introduction, and you can receive the results sent by telnet, but I feel that it took a long time, in fact, I don't know anything, because I didn't say a word about netty. This is also the problem I encountered when I first learned the framework. In fact, I was not satisfied with the level of use. I always wanted to know the principle and why it was used. In the end, I spent most of my time in it. The result is that the principle is good, but I don't feel much about the usage of the framework itself, so now I think everyone can change their thinking and pay more attention to the business.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981642&siteId=291194637