1. 引入依赖
netty 5.x 以后的版本已流产,建议使用4.x的版本
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.35.Final</version>
</dependency>
2. 聊天室服务端代码
public class ChatServer {
public static void main(String[] args) throws InterruptedException {
//创建两个线程组bossGroup和workerGroup, 含有的子线程NioEventLoop的个数默认为cpu核数的两倍
// bossGroup只是处理连接请求 ,真正的和客户端业务处理,会交给workerGroup完成
NioEventLoopGroup boosGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
//创建服务器对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* group:设置两个线程组bossGroup和workerGroup
* channel:使用NioServerSocketChannel作为服务端的通道实现
* option:初始化服务器连接队列大小为1024.
* 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。
* 多个客户端同时来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理。
* childHandler:创建通道初始化对象,设置处理器
*/
serverBootstrap
.group(boosGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//对workerGroup的SocketChannel设置处理器,设置客户端发来的数据的处理逻辑
//获取ChannelPipeline
ChannelPipeline pipeline = socketChannel.pipeline();
//向pipeline中加入解码器
pipeline.addLast("decoder",new StringDecoder());
//向pipeline中加入编码器
pipeline.addLast("encoder",new StringEncoder());
//向pipeline中加入业务Handler
pipeline.addLast(new ChatServerHandler());
}
});
System.out.println("聊天室服务端已启动。。。");
/**
* 服务端对象绑定 9000 端口并启动
* sync():由于bind方法是异步操作,使用sync()方法是等待异步操作执行完毕。
*/
ChannelFuture cf = serverBootstrap.bind(9000).sync();
/**
* 对通道关闭进行监听
* 由于closeFuture是异步操作,通过sync方法同步等待通道关闭处理完毕,这里会阻塞等待通道关闭完成
*/
cf.channel().closeFuture().sync();
}finally {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
服务端业务处理ChatServerHandler代码
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
//GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例,记录所有已在线的连接
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
//日期格式化器
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 如果连上服务端,触发channelActive方法
* @param ctx 上下文对象, 含有通道channel,管道pipeline
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//获取channel
Channel channel = ctx.channel();
//把当前客户端上线信息 推送到其他已在线的客户端
// 1. writeAndFlush()遍历channelGroup所有已在线的客户端
channelGroup.writeAndFlush("[ 客户端 ]"+channel.remoteAddress()+" 上线了! "+sdf.format(new Date())+"\n");
// 2. 把当前channel连接加入到channelGroup中去
channelGroup.add(channel);
//服务器端打印客户端上线信息
System.out.println(channel.remoteAddress()+" 上线了! "+"\n");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//获取channel
Channel channel = ctx.channel();
//客户端下线信息发送给其他客户端
channelGroup.writeAndFlush("[ 客户端 ]"+channel.remoteAddress()+" 下线了! "+"\n");
//服务器端打印客户端下线信息
System.out.println(channel.remoteAddress()+" 下线了! 还剩余:"+channelGroup.size()+" 个客户端!"+"\n");
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
//获取当前channel
Channel channel = channelHandlerContext.channel();
channelGroup.forEach(x -> {
if (channel != x) {
x.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + " 发送了消息:" + msg + "\n");
}else {
x.writeAndFlush("[ 自己 ]发送了消息:" + msg + "\n");
}
});
}
}
3. 聊天室客户端代码
public class ChatClient {
public static void main(String[] args) throws InterruptedException {
//客户端只需要一个事件循环组
NioEventLoopGroup group = new NioEventLoopGroup();
try {
//创建客户端启动对象
//注意客户端使用的不是 ServerBootstrap 而是 Bootstrap
Bootstrap bootstrap = new Bootstrap();
/**设置客户端相关参数
* group:设置线程组
* channel:使用NioSocketChannel作为客户端通道实现,注意服务端为NioServerSocketChannel
* handler:创建通道初始化对象,加入客户端处理器
*/
bootstrap
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
//加入处理器
ChannelPipeline pipeline = channel.pipeline();
//向pipeline中加入编码器
pipeline.addLast(new StringEncoder());
//向pipeline中加入解码器
pipeline.addLast(new StringDecoder());
//向pipeline中加入业务Handler
pipeline.addLast(new ChatClientHandler());
}
});
//启动客户端去连接服务端
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();
//得到channel
Channel channel = channelFuture.channel();
System.out.println("=============== " + channel.remoteAddress()+" ==================");
//客户端发送消息
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String msg = scanner.nextLine();
//通过客户端把输入内容发送到服务端
channel.writeAndFlush(msg);
}
//对关闭通道进行监听
// channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
客户端业务处理ChatClientHandler代码
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
//打印服务端发送的消息
System.out.println(msg.trim());
}
}