Fork me on GitHub

Netty源码剖析一简单介绍

Netty是什么
  1. 异步事件驱动框架,用于快速开发高性能服务端和客户端
  2. 封装了JDK底层BIO和NIO模型,提供高度可用的API
  3. 自带编码器解决拆包粘包问题,用户只关心业务逻辑
  4. 精心设计的reactor线程模型支持高并发海量连接
  5. 自带各种协议栈
原始的Socket

服务端

1
2
3
4
5
6
7
8
9
public class ServerBoot
{
private static final int PORT = 8000;
public static void main(String[] args)
{
Server server = new Server(PORT);
server.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Server
{
private ServerSocket serverSocket;
public Server(int port)
{
try{
this.serverSocket = new ServerSocket(port);
System.out.println("服务端启动成功,端口:"+port);
}catch (IOException e)
{
System.out.println("服务端启动失败");
}
}
public void start()
{
new Thread(new Runnable()
{
public void run()
{
doStart();
}
}).start();
}
private void doStart()
{
while (true)
{
try {
Socket client = serverSocket.accept();
new ClientHandler(client).start();
}catch (IOException e)
{
System.out.println("服务端异常");
}
}
}
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 8000;
private static final int SLEEP_TIME = 5000;

public static void main(String[] args) throws IOException
{
final Socket socket = new Socket(HOST, PORT);

new Thread(new Runnable() {
@Override
public void run() {
System.out.println("客户端启动成功!");
while (true) {
try {
String message = "hello world";
System.out.println("客户端发送数据: " + message);
socket.getOutputStream().write(message.getBytes());
} catch (Exception e) {
System.out.println("写数据出错!");
}
sleep();
}
}
}).start();

}
private static void sleep() {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ClientHandler {

public static final int MAX_DATA_LEN = 1024;
private final Socket socket;

public ClientHandler(Socket socket) {
this.socket = socket;
}
public void start() {
System.out.println("新客户端接入");
new Thread(new Runnable() {
@Override
public void run() {
doStart();
}
}).start();
}
private void doStart() {
try {
InputStream inputStream = socket.getInputStream();
while (true) {
byte[] data = new byte[MAX_DATA_LEN];
int len;
while ((len = inputStream.read(data)) != -1) {
String message = new String(data, 0, len);
System.out.println("客户端传来消息: " + message);
socket.getOutputStream().write(data);
}

}

} catch (IOException e) {
e.printStackTrace();
}
}
}

交互流程

Netty对于Socket的抽象

Netty基本组件

NioEventLoop:监听客户端的连接,监听客户端的读写

Channel:对连接的封装,在连接中可以进行数据的读写

Pipeline:对数据的读写可以看作逻辑处理链

ChannelHandler:逻辑处理链中处理的逻辑

ByteBuf:对数据的读写都是用ByteBuf来操作的