使用 NIO 搭建一个聊天室
使用 NIO 搭建一个聊天室
前面刚讲了使用 Socket 搭建了一个 Http Server,在最后我们使用了 NIO 对 Server 进行了优化,然后有小伙伴问到怎么使用 Socket 搭建聊天室,这节仍然使用 NIO 为基础进行搭建。
一、NIO 聊天室入门案例
该案例只有三个类:NioServer 聊天室服务端、NioClient 聊天室客户端、ClientThread 客户端线程。
服务端代码:
package com.fengsir.network.chatroom;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author FengZeng
* @Date 2022-01-24 17:01
* @Description Nio聊天室服务端
*/
public class NioServer {
/**
* 聊天室成员列表:
*/
Map<String, SocketChannel> memberChannels;
/**
* 端口
*/
private static final int PORT = 8000;
/**
* 选择器
*/
private Selector selector;
/**
* 管道
*/
private ServerSocketChannel server;
/**
* 缓冲
*/
private ByteBuffer buffer;
public NioServer() throws IOException {
// 初始化 Selector 选择器
this.selector = Selector.open();
// 初始化 Channel 通道
this.server = getServerChannel(selector);
// 初始化 Buffer 缓冲:1k
this.buffer = ByteBuffer.allocate(1024);
// 初始化聊天室成员列表
memberChannels = new ConcurrentHashMap<>();
}
/**
* 初始化Channel通道
*
* @param selector 选择器
* @return ServerSocketChannel
* @throws IOException
*/
private ServerSocketChannel getServerChannel(Selector selector) throws IOException {
// 开辟一个 Channel 通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 通道设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
// 通道注册绑定 Selector 选择器,通道中数据的事件类型为OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 通道绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
return serverSocketChannel;
}
/**
* 事件监听
*/
public void listen() throws IOException {
System.out.println("服务端启动......");
try {
// 据说用 while(true) 会多一个判断,用这种方式更好哈哈哈
for (;;){
// 作用:至少需要有一个事件发生,否则(如果count == 0)就继续阻塞循环
int count = selector.select();
if (count == 0) {
continue;
}
// 获取 SelectorKey 的集合
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iterator = keySet.iterator();
while (iterator.hasNext()) {
// 当前事件对应的 SelectorKey
SelectionKey key = iterator.next();
// 删除当前事件:表示当前事件已经被消费了
iterator.remove();
// 接收事件已就绪:
if (key.isAcceptable()) {
// 通过key获取ServerSocketChannel
ServerSocketChannel server = (ServerSocketChannel) key.channel();
// 通过 ServerSocketChannel 获取SocketChannel
SocketChannel channel = server.accept();
// channel 设置为非阻塞模式
channel.configureBlocking(false);
// channel 绑定选择器,当前事件切换为 读就绪
channel.register(selector, SelectionKey.OP_READ);
// 从channel中获取Host、端口等信息
System.out.println("客户端连接:"
+ channel.socket().getInetAddress().getHostName() + ":"
+ channel.socket().getPort());
// Read就绪事件
} else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
// 用于解密消息内容
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
// 将消息数据从通道 channel 读取到缓冲buffer
buffer.clear();
channel.read(buffer);
buffer.flip();
// 获取解密后的消息内容:
String msg = decoder.decode(buffer).toString();
if (!"".equals(msg)) {
System.out.println("收到:" + msg);
if (msg.startsWith("username:")) {
String username = msg.replaceAll("username:", "");
memberChannels.put(username, channel);
System.out.println("用户总数:" + memberChannels.size());
} else {
// 转发消息给客户端
String[] arr = msg.split(":");
if (arr.length == 3) {
// 发送者
String from = arr[0];
// 接收者
String to = arr[1];
// 发送内容
String content = arr[2];
System.out.println(from + " 发送给 " + to + " 的消息:" + content);
if (memberChannels.containsKey(to)) {
// 解密
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
// 给接收者发送消息
memberChannels.get(to).write(encoder.encode(CharBuffer.wrap(from + ":" + content)));
}
}
}
}
}
}
}
}catch (Exception e){
System.out.println("服务端启动失败......");
e.printStackTrace();
}finally {
try {
// 先关闭选择器,在关闭通道
// 调用 close() 方法将会关闭Selector,同时也会将关联的SelectionKey失效,但不会关闭Channel。
selector.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
// 服务端启动:
new NioServer().listen();
}
}
客户端线程类:
package com.fengsir.network.chatroom;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
/**
* @Author FengZeng
* @Date 2022-01-24 17:16
* @Description Nio聊天室客户端线程
*/
public class ClientThread extends Thread {
/**
* 解密
*/
private CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
/**
* 加密
*/
private CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
/**
* 选择器
*/
private Selector selector = null;
/**
* 通道
*/
private SocketChannel socket = null;
/**
* 通道key
*/
private SelectionKey clientKey = null;
/**
* 用户名
*/
private String username;
public ClientThread(String username) {
try {
// 创建一个Selector
selector = Selector.open();
// 创建Socket并注册
socket = SocketChannel.open();
socket.configureBlocking(false);
clientKey = socket.register(selector, SelectionKey.OP_CONNECT);
// 连接到远程地址
InetSocketAddress ip = new InetSocketAddress("localhost", 8000);
socket.connect(ip);
this.username = username;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 开辟读取事件的线程
*/
@Override
public void run() {
try {
// 监听事件(无限循环)
for (; ; ) {
// 监听事件
int count = selector.select();
if (count == 0) {
continue;
}
// 事件来源列表
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
// 删除当前事件
it.remove();
// 判断事件类型
if (key.isConnectable()) {
// 连接事件
SocketChannel channel = (SocketChannel) key.channel();
if (channel.isConnectionPending()) {
channel.finishConnect();
}
channel.register(selector, SelectionKey.OP_READ);
System.out.println("连接服务器端成功!");
// 发送用户名
send("username:" + this.username);
} else if (key.isReadable()) {
// 读取数据事件
SocketChannel channel = (SocketChannel) key.channel();
// 读取数据
ByteBuffer buffer = ByteBuffer.allocate(50);
channel.read(buffer);
buffer.flip();
String msg = decoder.decode(buffer).toString();
System.out.println("收到: " + msg);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭
try {
selector.close();
socket.close();
} catch (IOException ignored) {
}
}
}
/**
* 发送消息
*
* @param msg message
*/
public void send(String msg) {
try {
SocketChannel client = (SocketChannel) clientKey.channel();
client.write(encoder.encode(CharBuffer.wrap(msg)));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭客户端
*/
public void close() {
try {
selector.close();
socket.close();
} catch (IOException ignored) {
}
}
}
客户端类:
package com.fengsir.network.chatroom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @Author FengZeng
* @Date 2022-01-24 17:20
* @Description TODO
*/
public class NioClient {
public static void main(String[] args) {
// 当前客户端的用户名
String username = "fengzeng";
// 为当前客户端开辟一个线程
ClientThread client = new ClientThread(username);
client.start();
// 输入输出流
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
try {
// 循环读取键盘输入
String readline;
while ((readline = bfReader.readLine()) != null) {
if ("bye".equals(readline)) {
client.close();
System.exit(0);
}
// 发送消息
client.send(username + ":" + readline);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行效果图就是这样子,代码结合注释看,应该都能理解。

使用 NIO 搭建一个聊天室的更多相关文章
- netty实现消息中心(二)基于netty搭建一个聊天室
前言 上篇博文(netty实现消息中心(一)思路整理 )大概说了下netty websocket消息中心的设计思路,这篇文章主要说说简化版的netty聊天室代码实现,支持群聊和点对点聊天. 此demo ...
- Jaguar_websocket结合Flutter搭建简单聊天室
1.定义消息 在开始建立webSocket之前,我们需要定义消息,如:发送人,发送时间,发送人id等.. import 'dart:convert'; class ChatMessageData { ...
- SpringBoot 搭建简单聊天室
SpringBoot 搭建简单聊天室(queue 点对点) 1.引用 SpringBoot 搭建 WebSocket 链接 https://www.cnblogs.com/yi1036943655/p ...
- IO、NIO实现简单聊天室,附带问题解析
本篇文章主要使用IO和NIO的形式来实现一个简单的聊天室,并且说明IO方法存在的问题,而NIO又是如何解决的. 大概的框架为,先提供思路和大概框架图--代码--问题及解决方式,这样会容易看一点 ...
- 基于react+react-router+redux+socket.io+koa开发一个聊天室
最近练手开发了一个项目,是一个聊天室应用.项目虽不大,但是使用到了react, react-router, redux, socket.io,后端开发使用了koa,算是一个比较综合性的案例,很多概念和 ...
- SilverLight搭建WCF聊天室详细过程[转]
http://www.silverlightchina.net/html/zhuantixilie/getstart/2011/0424/7148.html 默认节点 SilverLight搭建WCF ...
- 使用.NET Core和Vue搭建WebSocket聊天室
博客地址是:https://qinyuanpei.github.io. WebSocket是HTML5标准中的一部分,从Socket这个字眼我们就可以知道,这是一种网络通信协议.WebSocket是 ...
- 使用原生node写一个聊天室
在学习node的时候都会练习做一个聊天室的项目,主要使用socket.io模块和http模块.这里我们使用更加原始的方式去写一个在命令行聊天的聊天室. http模块,socket.io都是高度封装之后 ...
- 利用socket.io构建一个聊天室
利用socket.io来构建一个聊天室,输入自己的id和消息,所有的访问用户都可以看到,类似于群聊. socket.io 这里只用来做一个简单的聊天室,官网也有例子,很容易就做出来了.其实主要用的东西 ...
随机推荐
- PHP-文件上传封装类
<?php $file = $_FILES['img']; $obj = new File(); $res = $obj->upload($file,'upload'); if($res) ...
- XSHELL的坑
今天使用XSHELL连接虚拟机上的CENTOS7 ,刚开始还可以正常连接,后来再就连接不上. 检查了半天SSH服务都检查过了运行正常, 重启,检查配置文件. 都OK没问题就是连接不上,折腾半天还是不行 ...
- 原生 JS 实现 HTML 转 Markdown,以及其实现逻辑
之前因为一些需要,需要转换部分 HTML 标签成 markdown 格式,但是不知不觉就完善到一个相对完整的函数. 然后我就封装成了一个文件放在了 github ,也简单做了两个示例网页. HTML ...
- Source Code Reading for Vue 3: How does `hasChanged` work?
Hey, guys! The next generation of Vue has released already. There are not only the brand new composi ...
- MariaDB开启日志审计功能
对于MySQL.Percona.MariaDB三家都有自己的审计插件,但是MySQL的审计插件是只有企业版才有的,同时也有很多第三方的的MySQL的审计插件,而Percona和MariaDB都是GPL ...
- 前端好用API之Fullscreen
前情 在前端开发需求中,特别网页有视频需求时,需要做视频全屏功能,或者在某些可视化大屏项目也要做全屏. Fullscreen介绍 让你可以简单地控制浏览器,使得一个元素与其子元素,如果存在的话,可以占 ...
- Skye无人机刷Betaflight详细图文教程
前言 首先十分感谢B站TASKBL up主的视频教程以及他的耐心指导,视频链接Skye 原机主板刷BetaFlight 参考教程_哔哩哔哩_bilibili.整个改造过程耗时三天,现把改造过程以及遇 ...
- 无传感FOC控制中的转子位置和速度确定方法一
使用PLL估算器在无感的情况下,估计转子的角度和角速度 PLL估算器的工作原理基于反电动势的d分量在稳态下等于零,其框图如下: ΚΦ 表示电压常量,下面给出了电气转速计算中使用的归 一化 ΚΦ : ...
- CEPH-2:rbd功能详解及普通用户应用ceph集群
ceph集群rbd使用详解 一个完整的ceph集群,可以提供块存储.文件系统和对象存储. 本节主要介绍rbd存储功能如何灵活的使用,集群背景: $ ceph -s cluster: id: 53717 ...
- List 和 Map 区别?
表面来看,List是一个只是存放单个元素的集合,List集合所包含的元素可以重复,元素按放入的先后顺序来存放,程序可以通过元素的索引来读取元素,因此List相当于一个动态数组:Map则是一个存放key ...