使用 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 这里只用来做一个简单的聊天室,官网也有例子,很容易就做出来了.其实主要用的东西 ...
随机推荐
- Python 递归函数返回值为 None 的解决办法
在使用 Python 开发的过程中,避免不了会用到递归函数.但递归函数的返回值有时会出现意想不到的情况. 下面来举一个例子: >>> def fun(i): ... i += 1 . ...
- Kubernetes系列(二)Service
作者: LemonNan 原文地址: https://juejin.im/post/6863704173931593736 Service Kubernetes 的 Service 可以为一组具有相同 ...
- BBS项目分布搭建三(个人站点时间归档补充,实现侧边栏跳转、无线级分类、实现文章详情页展示功能)
BBS项目分布搭建三(个人站点时间归档补充,) 1. 个人站点时间归档 """ settings.py设置最好更改以下: LANGUAGE_CODE = 'zh-hans ...
- social network 中Clustering Coefficient 相关笔记2
breath_first search 改变了原图的连接情况.
- LGP3426题解
真是不管什么时候来做这道题都会觉得很神仙呐... 观察一下,如果存在一个合法的印章,那么这个印章一定是这个串的前缀,也是这个串的后缀. 即合法的印章一定是原串的 \(\rm Border\). 于是设 ...
- HIve的基本使用
WHERE从表中筛选行: SELECT从表中查询指定的列: group by在列上做聚合. -- 假设数据文件的内容,字段之间以ASCII 001(ctrl-A)分隔,行之间以换行分隔. CREATE ...
- (一)【转】asp.net mvc生成验证码
网站添加验证码,主要为防止机器人程序批量注册,或对特定的注册用户用特定程序暴力破解方式,以进行不断的登录.灌水等危害网站的操作.验证码被广泛应用在注册.登录.留言等提交信息到服务器端处理的页面中. ...
- 22.2.14session和反反爬处理
22.2.14 session和反反爬处理 1.session: requests库包含session,都是用来对一个url发送请求,区别在于session是一连串的请求,在session请求过程中c ...
- 数据库篇:mysql日志类型之 redo、undo、binlog
前言 可以说mysql的多数特性都是围绕日志文件实现,而其中最重要的有以下三种 redo 日志 undo 日志 binlog 日志 关注公众号,一起交流:微信搜一搜: 潜行前行 1 redo日志 in ...
- Python中将字典转为成员变量
技术背景 当我们在Python中写一个class时,如果有一部分的成员变量需要用一个字典来命名和赋值,此时应该如何操作呢?这个场景最常见于从一个文件(比如json.npz之类的文件)中读取字典变量到内 ...