 Netty快速入⻔
Netty快速入⻔
  开发环境:JDK8 + Idea
# 3.1、创建itcast-MyRPC项⽬
pom.xml⽂件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>cn.itcast.myrpc</groupId> <artifactId>itcast-MyRPC</artifactId> <version>1.0-SNAPSHOT</version>
<dependencies>
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.50.Final</version> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
<build>
<plugins> <!-- java编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> 
  </plugin>
  </plugins>
  </build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 3.2、服务端
# 3.2.1、MyRPCServer
package cn.itcast.myrpc.server;
import cn.itcast.myrpc.server.handler.MyChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class MyRPCServer
{
    public void start(int port) throws Exception
    {
        // 主线程,不处理任何业务逻辑,只是接收客户的连接请求 
      	EventLoopGroup boss = new NioEventLoopGroup(1); 
     	 // ⼯作线程,线程数默认是:cpu*2 
     	 EventLoopGroup worker = new NioEventLoopGroup();
        try
        {
            // 服务器启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker) //设置线程组
                .channel(NioServerSocketChannel.class) //配置server通道
                .childHandler(new MyChannelInitializer()); //worker线程的处理器
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("服务器启动完成,端⼝为:" + port);
            //等待服务端监听端⼝关闭 
          	future.channel().closeFuture().sync();
        }
        finally
        { 
          //优雅关闭 
          boss.shutdownGracefully();
          worker.shutdownGracefully();
        }
    }
}
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
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
# 3.2.2、MyChannelInitializer
package cn.itcast.myrpc.server.handler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
/**
* ChannelHandler的初始化
*/
public class MyChannelInitializer extends ChannelInitializer <SocketChannel> {
   @Override
  	protected void initChannel(SocketChannel ch) throws Exception {
        //将业务处理器加⼊到列表中
        ch.pipeline().addLast(new MyChannelHandler());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3.2.3、MyChannelHandler
package cn.itcast.myrpc.server.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class MyChannelHandler extends ChannelInboundHandlerAdapter {
    /**
    * 获取客户端发来的数据
    * 
    * @param ctx 
    * @param msg 
    * @throws Exception 
    */
    @Override 
  	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        String msgStr = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("客户端发来数据:" + msgStr);
      
        //向客户端发送数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8));
    }
    /** 
    * 异常处理 
    * 
    * @param ctx 
    * @param cause 
    * @throws Exception 
    */
    @Override 
  	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
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
38
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
38
# 3.2.4、测试⽤例
package cn.itcast.myrpc;
import cn.itcast.myrpc.server.MyRPCServer;
import org.junit.Test;
public class TestServer {
    @Test 
    public void testServer() throws Exception {
        MyRPCServer myRPCServer = new MyRPCServer();
      
        myRPCServer.start(5566);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 3.2.5、测试

可以看到,客户端发送数据到服务端。
# 3.3、客户端
# 3.3.1、MyRPCClient
package cn.itcast.myrpc.client;
import cn.itcast.myrpc.client.handler.MyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class MyRPCClient {
    public void start(String host, int port) throws Exception {
      
        //定义⼯作线程组 
      EventLoopGroup worker = new NioEventLoopGroup();
      
        try { 
          //注意:client使⽤的是Bootstrap 
          Bootstrap bootstrap = new Bootstrap(); 
          bootstrap.group(worker)
            .channel(NioSocketChannel.class) //注意:client使⽤的是 NioSocketChannel 
            .handler(new MyClientHandler());
          
            //连接到远程服务 
          ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
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
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
# 3.3.2、MyClientHandler
package cn.itcast.myrpc.client.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class MyClientHandler extends SimpleChannelInboundHandler <ByteBuf> {
    @Override 
  protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("接收到服务端的消息:" + msg.toString(CharsetUtil.UTF_8));
    }
    
  @Override 
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 向服务端发送数据
        String msg = "hello";
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
    }
    
  @Override 
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
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
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
# 3.3.3、测试⽤例
package cn.itcast.myrpc;
import cn.itcast.myrpc.client.MyRPCClient;
import org.junit.Test;
public class TestClient {
    @Test 
  	public void testClient() throws Exception {
        new MyRPCClient().start("127.0.0.1", 5566);
    }
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 3.3.4、测试
客户端:

服务端:

上次更新: 2025/04/03, 11:07:08
