Why does Netty transmit fast

Principle of HTTP server:

  1  创建一个ServerSocket,监听并绑定一个端口
  2  一系列客户端来请求这个端口
  3  服务器使用Accept,获得一个来自客户端的Socket连接对象
 
  4  启动一个新线程处理连接
       1) 读Socket,得到字节流
       2) 解码协议,得到Http请求对象
       3) 处理Http请求,得到一个结果,封装成一个HttpResponse对象
       4) 编码协议,将结果序列化字节流
       5) 写Socket,将字节流发给客户端
 
  5  继续循环步骤3

The HTTP server is called an HTTP server because the encoding and decoding protocol is the HTTP protocol. If the protocol is the Redis protocol, then it becomes a Redis server, if the protocol is WebSocket, then it becomes a WebSocket server, and so on.

Using Netty, you can customize the codec protocol and implement your own specific protocol server.

Reasons why NIO is faster than BIO:

1. In BIO, the process of waiting for the client to send data is blocked, which results in a situation where one thread can only handle one request,
and the maximum number of threads that the machine can support is limited, which is why BIO cannot support high The reason for concurrency.

2. In NIO, when a Socket is established, Thread does not block to accept the Socket, but passes the request to the Selector. The
Selector will continue to traverse all the Sockets. Once a Socket is established, he The Thread will be notified, and then the Thread will process
the data and then return it to the client-this process is blocked, so that a Thread can handle more requests.

Why does Netty transmit fast

Netty's fast transmission actually relies on a feature of NIO-zero copy. We know that Java's memory includes heap memory, stack memory, string constant pool, etc.,
among which heap memory is the largest piece of memory space, and it is also the place where Java objects are stored. Generally, if our data needs to be read from IO to the heap The memory
needs to go through the Socket buffer in the middle, which means that a piece of data will be copied twice to reach its end. If the amount of data is large, it will cause unnecessary waste of resources.
In response to this situation, Netty uses another major feature in NIO-zero copy. When he needs to receive data, he will open up a memory outside the heap memory, and the
data will be read directly from the IO to that memory. Go, these data can be directly manipulated through ByteBuf in netty, thus speeding up the transmission.

 

Guess you like

Origin blog.csdn.net/qq_32445015/article/details/102398636