1、引入 jar 包
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
2、Netty 服务端
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//1、创建两个线程池对象
// bossGroup 负责接收用户连接
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// workGroup 负责接收用户的 io读写操作
NioEventLoopGroup workGroup = new NioEventLoopGroup();
//2、创建启动引导类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//3、设置启动引导类
//添加到组中,两个线城池,第一个位置的线程池就负责接收,第二个参数就负责读写
serverBootstrap.group(bossGroup,workGroup)
//给我们当前设置一个通道类型
.channel(NioServerSocketChannel.class)
//绑定一个初始化监听
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
//获取pipeLine
ChannelPipeline pipeline = nioSocketChannel.pipeline();
//绑定编码
pipeline.addFirst(new StringEncoder());
pipeline.addLast(new StringDecoder());
//绑定我们的业务逻辑
pipeline.addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
//获取入栈信息,打印客户端传递的数据
System.out.println(msg);
}
});
}
});
//4、启动引导类绑定端口
ChannelFuture future = serverBootstrap.bind(9999).sync();
//5、关闭通道
future.channel().closeFuture();
}
}
3、Netty 客户端
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
//1、创建连接池对象
NioEventLoopGroup group = new NioEventLoopGroup();
//2、创建客户端的启动引导类 Bootstrap
Bootstrap bootstrap = new Bootstrap();
//3、配置启动引导类
bootstrap.group(group)
//设置通道为nio
.channel(NioSocketChannel.class)
//设置Channel初始化监听
.handler(new ChannelInitializer<Channel>() {
//当前该方法监听channel是否初始化
@Override
protected void initChannel(Channel channel) throws Exception {
//设置编码
channel.pipeline().addFirst(new StringEncoder());
}
});
//4、使用启动引导类连接服务器,获取一个 channel
Channel channel = bootstrap.connect("127.0.0.1", 9999).channel();
//5、循环写数据给服务器
while (true){
channel.writeAndFlush("hello server... this is client ..");
Thread.sleep(2000);
}
}
}