一、案例要求
实例要求:
- 编写一个 NIO 群聊系统, 实现服务器端和客户端之间的数据简单通讯(非 阻塞)
- 实现多人群聊
- 服务器端: 可以监测用户上线, 离线,并实现消息转发功能
- 客户端: 通过channel 可以无阻塞发送消息给其它所有用户,同时可以接受 其它用户发送的消息(有服务器转发得到)
- 目的: 进一步理解NIO非阻塞网络编程机制
实现效果:
思路步骤:
- 先编写服务器端
- 服务器启动并监听 6667
- 服务器接收客户端信息,并实现转发 [处理上线和离线]
- 编写客户端
- 连接服务器
- 发送消息
- 接收服务器消息
二、服务器端
public class GroupChatServer {
//定义属性
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6667;
//构造器
//初始化工作
public GroupChatServer() {
try {
//得到选择器
selector = Selector.open();
System.out.println("selector = " + selector);
//获取 ServerSocketChannel
listenChannel = ServerSocketChannel.open();
//绑定端口
listenChannel.socket().bind(new InetSocketAddress(PORT));
//设置非阻塞模式
listenChannel.configureBlocking(false);
//将该 listenChannel 注册到selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
//服务器监听
public void listen() {
System.out.println("监听线程: " + Thread.currentThread().getName());
try {
//循环处理
while (true) {
int count = selector.select();
//有事件需要处理
if (count > 0) {
//遍历得到的 selectionKey 集合
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
//取出 SelectionKey
SelectionKey key = keyIterator.next();
//监听到accept
if (key.isAcceptable()) {
//创建一个SocketChannel
SocketChannel socketChannel = listenChannel.accept();
//设置非阻塞模式
socketChannel.configureBlocking(false);
//注册到选择器
socketChannel.register(selector, SelectionKey.OP_READ);
//提示
System.out.println(socketChannel.getRemoteAddress() + " 上线");
}
//通道发送read事件,即通道是可读的状态
if (key.isReadable()) {
//处理读(专门写方法...)
read(key);
}
//当前的key 删除,防止重复处理
keyIterator.remove();
}
} else {
System.out.println("等待...");
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
//读取客户端信息
private void read(SelectionKey key) {
//得到关联的 Channel
SocketChannel socketChannel = null;
try {
//得到 channel
socketChannel = (SocketChannel) key.channel();
//创建 buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取数据
int count = socketChannel.read(buffer);
//根据 count 的值去做处理
if (count > 0) {
//把缓存区的数据转成字符串
String msg = new String(buffer.array());
//输出该消息
System.out.println("form 客户端:" + msg);
//转发消息:向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
sentInfoToOtherClients(msg, socketChannel);
}
}catch (IOException e) {
try {
System.out.println(socketChannel.getRemoteAddress() + " 离线了..");
//取消注册
key.cancel();
//关闭通道
socketChannel.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//转发消息给其它客户(通道)
private void sentInfoToOtherClients(String msg, SocketChannel self) throws IOException{
System.out.println("服务器转发消息中...");
System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
//遍历 所有注册到selector 上的 SocketChannel,并排除 self
for (SelectionKey key : selector.keys()) {
//通过 key 获取到对应的 channel
Channel targetChannel = key.channel();
//排除自己
if (targetChannel instanceof SocketChannel && targetChannel != self) {
//转型
SocketChannel dest = (SocketChannel) targetChannel;
//将msg存储到 buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//将 buffer 的数据写入通道
dest.write(buffer);
}
}
}
public static void main(String[] args) {
//创建服务器对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
三、客户端
public class GroupChatClient {
//定义相关的属性
// 服务器的ip
private static final String HOST = "127.0.0.1";
//服务器端口
private static final Integer PORT = 6667;
private Selector selector;
private SocketChannel socketChannel;
private String userName;
//构造器,完成初始化工作
public GroupChatClient() {
try {
//获取选择器
selector = Selector.open();
System.out.println("selector = " + selector);
//连接服务器
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
//设置非阻塞
socketChannel.configureBlocking(false);
//将 socketChannel 注册到 selector
socketChannel.register(selector, SelectionKey.OP_READ);
//得到 userName
userName = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(userName + " is ok...");
} catch (IOException e) {
e.printStackTrace();
}
}
//向服务器发送消息
public void sendInfo(String info) {
info = userName + "说:" + info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
//读取从服务器端回复的消息
public void readInfo() {
try {
int readChannels = selector.select();
//有可以用的通道
if (readChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
//得到相关的通道
SocketChannel socketChannel = (SocketChannel) key.channel();
//得到一个 Buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取
socketChannel.read(buffer);
//把读到的缓冲区的数据转成字符串
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
}
//删除当前的selectionKey, 防止重复操作
iterator.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//启动客户端
GroupChatClient chatClient = new GroupChatClient();
//启动一个线程,每隔3秒,读取从服务器发送的数据
new Thread() {
@Override
public void run() {
System.out.println("读取信息");
chatClient.readInfo();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
//发送数据给服务器
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?