一、实例要求:
1)编写一个Netty群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
2)实现多人群聊
3)服务器端:可以监测用户上线,离线,并实现消息转发功能。
4)客户端:通过channel可以无阻塞发送消息给其他所有用户,同时可以接受其他用户发送的消息(有服务器转发得到)
5)目的:进一步理解Netty非阻塞网络编程机制。
二、以下为实现代码
1.服务器端GroupChatServer.java
package com.tfq.netty.netty.groupchat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* @author: fqtang
* @date: 2024/04/03/13:39
* @description: 描述
*/
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(8);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
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 {
//获取到pipeline
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入一个解码器
pipeline.addLast("decoder", new StringDecoder());
//向pipeline加入一个编码器
pipeline.addLast("encoder", new StringEncoder());
//加入自己的业务处理handler
pipeline.addLast(new GroupChatServerHandler());
}
});
System.out.println("netty 服务器启动");
ChannelFuture channelFuture = serverBootstrap.bind(port)
.sync();
channelFuture.channel()
.closeFuture()
.sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new GroupChatServer(7888).run();
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}
服务器端的handler处理:
package com.tfq.netty.netty.groupchat;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
* @author: fqtang
* @date: 2024/04/03/13:53
* @description: 描述
*/
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 定义一个channel组,管理所有的channel
* GlobalEventExecutor.INSTANCE是全局的事件执行器,是一个单例
*/
private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 表示连接建立,一旦连接,第一个被执行
* 将当前channel加入到 channelGroup
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
//将该客户加入聊天的信息推送给其他在线的客户端
//该方法会将channelGroup 中所有的channel 遍历,并发送消息,我们不需要自己遍历
channels.writeAndFlush(sdf.format(new Date())+" [客户端]" + channel.remoteAddress() + " 加入聊天\n");
channels.add(channel);
}
/**
* 表示channel 处于活动上线,提示 xx上线
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel()
.remoteAddress() + " 在[ "+sdf.format(new Date())+" ] 上线了~");
}
/**
* 表示channel 处于离线,提示 xx离线
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel()
.remoteAddress() + "在 "+sdf.format(new Date())+" 离线了~");
}
/**
* 断开连接,将XX客户离开信息推送给当前在线的客户
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channels.writeAndFlush("[客户端]" + channel.remoteAddress() + "在 【"+ sdf.format(new Date()) +"】 离开\n");
System.out.println("移除通道"+channel.hashCode()+",当前通道总数:" + channels.size());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//获取当前通道channel
Channel channel = ctx.channel();
//这时我们遍历channels,根据不同的情况,返回不同的不同消息
channels.forEach(c -> {
if(channel !=c){//不是当前的channel,直接打印消息
//把当前通道的消息转发给其他通道了
c.writeAndFlush("[客户]" + channel.remoteAddress()+ "在 【"+ sdf.format(new Date()) + "】 发送了消息:"+ msg +" \n");
}else {
c.writeAndFlush("【自己】在 【"+ sdf.format(new Date()) +"】 发送了消息"+msg+"\n");
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//关闭通道
ctx.close();
System.out.println("在 【"+sdf.format(new Date()) +"】 关闭通道,通道总数:" + channels.size());
}
}
2.客户端GroupChatClient.java
package com.tfq.netty.netty.groupchat;
import java.util.Scanner;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* @author: fqtang
* @date: 2024/04/04/7:54
* @description: 描述
*/
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() {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//得到pipeline
ChannelPipeline pipeline = ch.pipeline();
//加入相关handler的解码器
pipeline.addLast("decoder", new StringDecoder());
//加入相关handler的编码器
pipeline.addLast("encoder", new StringEncoder());
//加入自定义的handler
pipeline.addLast(new GroupChatClientHandler());
}
});
//连接服务器返回通道
ChannelFuture channelFuture = bootstrap.connect(host, port)
.sync();
Channel channel = channelFuture.channel();
if(channelFuture.isSuccess()) {
System.out.println("本地ip:"+channel.localAddress()+",连接服务器ip: "+channel.remoteAddress() + " 成功");
}
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()) {
channel.writeAndFlush(scanner.nextLine());
}
//给关闭监听进行通道
channel.closeFuture()
.sync();
} catch(InterruptedException e) {
throw new RuntimeException(e);
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new GroupChatClient("127.0.0.1", 7888).run();
}
}
客户端的handler处理
package com.tfq.netty.netty.groupchat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @author: fqtang
* @date: 2024/04/04/8:16
* @description: 描述
*/
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
先运行GroupChatServer.java,然后运行多个GroupChatClient客户端。若用Idea开发则设置运行多个 客户。如下图:
运行如下图所示:
完毕。