【概述】
实现一个网络群聊工具。参与聊天的客户端消息是通过服务端进行广播的。
主要由两块组成:聊天服务器端(ChatServer)和聊天客户端(ChatClient)。
聊天服务器(ChatServer)功能概述 :
1.监听所有客户端的接入、断线
2.有客户端A接入聊天室时,将接入消息发给除了客户端A的其他客户端
3.当客户端A退出聊天室时,将退出消息发给除了客户端A的其他客户端
4.当客户端A发送消息到聊天室时,将消息转发给除了客户端A的其他客户端
聊天客户端(ChatClient)功能概述 :
1.发送消息至聊天服务器
2.接收聊天服务器发送过来的所有消息
【pom依赖】
<!--netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
【服务端启动器 ChatServer 】
package com.test.server; 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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; /**
* 群聊服务端
*
*/
public class ChatServer {
private final int port; public ChatServer(int port) {
this.port = port;
} public void start() throws InterruptedException {
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
//添加一个基于行的解码器
pipeline.addLast(new LineBasedFrameDecoder(2048));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ChatServerHandler());
} }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = serverBootstrap.bind(port).sync();
System.out.println("服务器已启动");
future.channel().closeFuture().sync();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
} public static void main(String[] args) throws InterruptedException {
new ChatServer(8888).start();
}
}
【ChatServerHandler】
package com.test.server; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor; /**
* 处理聊天服务器的各种情况
*
*/
public class ChatServerHandler extends ChannelInboundHandlerAdapter {
// 创建一个ChannelGroup,其是一个线程安全的集合,其中存放着与当前服务器相连接的所有Active状态的Channel
// GlobalEventExecutor是一个单例、单线程的EventExecutor,是为了保证对当前group中的所有Channel的处理
// 线程是同一个线程
private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); // 只要有客户端Channel给当前的服务端发送了消息,那么就会触发该方法的执行
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 获取到向服务器发送消息的channel
Channel channel = ctx.channel();
// 这里要实现将消息广播给所有group中的客户端Channel
// 发送给自己的消息与发送给大家的消息是不一样的
group.forEach(ch -> {
if (ch != channel) {
ch.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
} else {
channel.writeAndFlush("me:" + msg + "\n");
}
});
} // 只要有客户端Channel与服务端连接成功就会执行这个方法
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 获取到当前与服务器连接成功的channel
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress() + "---上线");
group.writeAndFlush(channel.remoteAddress() + "---上线\n");
// 将当前channel添加到group中
group.add(channel);
} // 只要有客户端Channel断开与服务端的连接就会执行这个方法
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 获取到当前要断开连接的Channel
Channel channel = ctx.channel();
System.out.println(channel.remoteAddress() + "------下线");
group.writeAndFlush(channel.remoteAddress() + "下线,当前在线人数:" + group.size() + "\n"); // group中存放的都是Active状态的Channel,一旦某Channel的状态不再是Active,
// group会自动将其从集合中踢出,所以,下面的语句不用写
// remove()方法的应用场景是,将一个Active状态的channel移出group时使用
// group.remove(channel);
} /**
* 当Channel中的数据在处理过程中出现异常时会触发该方法的执行
*
* @param ctx 上下文
* @param cause 发生的异常对象
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} }
【客户端启动类ChatClient】
package com.test.client; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* 群聊客户端
*
*/
public class ChatClient {
private final String host; private final int port; public ChatClient(String host, int port) {
this.host = host;
this.port = port;
} public void start() {
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(2048));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ChatClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
// 获取键盘输入
InputStreamReader is = new InputStreamReader(System.in, "UTF-8");
BufferedReader br = new BufferedReader(is);
// 将输入的内容写入到Channel
while (true) {
//br.readLine()中执行fill()方法获取输入数据,获取不到时会发生阻塞,直到获取到数据为止
future.channel().writeAndFlush(br.readLine() + "\r\n");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) {
new ChatClient("127.0.0.1", 8888).start();
}
}
【ChatClientHandler】
package com.test.client; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; /**
* 客户端处理
*
*/
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
【运行结果】
[1.启动群聊服务端]
[2.启动群聊客户端01]
[2.启动群聊客户端02]
[3.发送消息测试]
[4.下线测试]