目录
需求功能
客户端:
- 连接服务器,可以从键盘输入读取数据发送给服务器端
- 接收服务端的发来的消息
服务器端:
- 可以监测客户端(用户)上线、离线
- 实现消息转发给其它客户端(用户)
- 向其它客户端(用户)提示某个客户端的加入和离开
实现思路
客户端:
- 首先用户发送和接收的是字符串,在pipeline加入字符串解码器(StringDecoder)和字符串编码器(StringEncoder)
- 与服务端建立连接后,使用Scanner从键盘循环读取数据,然后向连接后的Channel中发送数据
- 为了方便业务处理器选择SimpleChannelInboundHandler,能够直接把解码器得到的字符串以参数的形式直接传入到回调方法中
服务器端:
- 同客户端一样,在pipeline加入字符串解码器(StringDecoder)和字符串编码器(StringEncoder)
- 同客户端一样选择SimpleChannelInboundHandler做为业务处理器,使用ChannelGroup(集合)保存所有客户端
- channelActive方法表示channel处于活动状态,提示xxx上线了
- channelInactive方法表示channel处于不活动状态,提示xxx下线了
- handlerAdded方法表示连接建立,当客户端上来一旦连接时被执行,在此方法中向channel集合所有用户通知xxx加入聊天室
- handlerRemoved方法表示断开连接,当客户端与服务器断开连接时被执行,在此方法中向channel集合有用户通知xxx离开聊天室
服务端实现
服务器实现类
public class NettyGroupChatServer {
private int port;
public NettyGroupChatServer(int port){
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGoup = new NioEventLoopGroup(8);
try{
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGoup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// bytebuffer->String
pipeline.addLast("decoder", new StringDecoder());
// string->bytebuffer
pipeline.addLast("encoder", new StringEncoder());
// 业务处理器
pipeline.addLast(new GroupChatServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGoup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new NettyGroupChatServer(7777).run();
}
}
业务处理器:
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
private static ChannelGroup channelGroup = 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.writeAndFlush("【客户端】 " + channel.remoteAddress() + " 加入了聊天" + sdf.format(new Date()) + "\n");
channelGroup.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("【客户端】" + channel.remoteAddress() + " 离开了\n" );
System.out.println("channelGroup size" + channelGroup.size());
}
// 表示 channel 处于活动状态, 提示 xx 上线
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 上线了~");
}
// 表示 channel 处于不活动状态, 提示 xx 离线了
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 离线了~");
}
/**
* 读取数据
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 获取当时channel,把信息转发到除channelGroup中的其它chanel上
Channel channel = ctx.channel();
channelGroup.forEach(ch ->{
if (channel != ch){
ch.writeAndFlush("[客户] " + channel.remoteAddress() + " 发送了消息" + msg + "\n");
}else{
ch.writeAndFlush("[自已]发送了消息" + msg + "\n");
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
客户端实现
客户端启动类:
public class NettyGroupChatClient {
private final String host;
private final int port;
public NettyGroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try{
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// bytebuffer->String
pipeline.addLast("decoder", new StringDecoder());
// string->bytebuffer
pipeline.addLast("encoder", new StringEncoder());
// 业务处理器
pipeline.addLast(new GroupChatClientHandler());
}
});
// 连接服务端
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
// 获取通道
Channel channel = channelFuture.channel();
// 发送数据
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String content = scanner.nextLine();
channel.writeAndFlush(content + "\r\n");
}
}finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new NettyGroupChatClient("127.0.0.1", 7777).run();
}
}
客户端业务处理器:
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
/**
* 读取数据
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}