1. 实例要求
- 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
- 实现多人群聊
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发 得到)
- 目的:进一步理解 Netty 非阻塞网络编程机制
2. 代码
GroupChatServer.java
public class GroupChatServer {
// 监听端口
private int port;
public GroupChatServer(int port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 加入编码-解码器
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// 加入自己的handler
pipeline.addLast(new GroupChatServerHandler());
}
});
System.out.println("GroupChatServer is ready...\n");
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new GroupChatServer(5758).run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GroupChatServerHandler.java
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 定义一个 Channel 组,管理所有的 Channel
* GlobalEventExecutor.INSTANCE 全局执行器
*/
public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
/**
* 日期格式
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Channel连接完毕 处于活动状态 触发
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 服务端提示 xxx客户端上线了
System.out.println(String.format("[客户端%s]上线了~ %s\n", ctx.channel().remoteAddress(), sdf.format(new Date())));
}
/**
* Channel断开完毕 非活动状态 触发
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 服务端提示 xxx客户端离线
System.out.println(String.format("[客户端%s]离线了~ %s\n", ctx.channel().remoteAddress(), sdf.format(new Date())));
}
/**
* Channel连接建立 触发
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
// 向其他Channel广播 该Channel已连接的消息
String msg = String.format("[客户端%s]加入聊天 %s\n", channel.remoteAddress(), sdf.format(new Date()));
channelGroup.writeAndFlush(msg);
// 把该Channel加入到Channel组中
channelGroup.add(channel);
}
/**
* Channel断开连接 触发
* @param ctx
* @throws Exception
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
// 将该Channel离线消息广播给其他Channel
// Channel断开会自动从ChannelGroup中移除,无需手动移除
Channel channel = ctx.channel();
String msg = String.format("[客户端%s]离开了 %s\n", channel.remoteAddress(), sdf.format(new Date()));
channelGroup.writeAndFlush(msg);
}
/**
* 读事件 触发
* @param ctx 上下文
* @param msg 客户端发来的数据
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 将该Channel消息广播给其他Channel
Channel channel = ctx.channel();
channelGroup.forEach(ch -> {
if (channel == ch) {
ch.writeAndFlush(String.format("[自己%s %s]: %s\n", channel.remoteAddress(), sdf.format(new Date()), msg));
} else {
ch.writeAndFlush(String.format("[客户端%s %s]: %s\n", channel.remoteAddress(), sdf.format(new Date()), msg));
}
});
}
/**
* 捕获异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Channel channel = ctx.channel();
if (channel.isActive()) {
cause.printStackTrace();
} else {
channel.close();
System.out.println(String.format("[客户端%s]离线~\n", channel.localAddress()));
}
}
}
GroupChatClient
public class GroupChatClient {
// 主机与端口
private final String host;
private final int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//添加 编码-解码器
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// 加入自定义handler
pipeline.addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 显示服务端发送的消息
System.out.println(msg.trim());
}
});
}
});
// 连接服务器
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
// 创建客户端个输入扫描器
Channel channel = channelFuture.channel();
System.out.println(String.format("------%s------\n", channel.localAddress()));
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
// 发送到服务器
channel.writeAndFlush(scanner.nextLine());
}
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new GroupChatClient("127.0.0.1", 5758).run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3 运行结果
server
client1
client2