Java NIO实战之多人聊天室
作者:红字V 发布时间:2022-02-28 15:05:00
标签:java,NIO,聊天室
本文实例为大家分享了Java NIO实战之多人聊天室的具体代码,供大家参考,具体内容如下
NIO服务端
public class NioServer {
/**
* 启动
*/
public void start() throws IOException {
/**
* 1. 创建Selector
*/
Selector selector = Selector.open();
/**
* 2. 通过ServerSocketChannel创建channel通道
*/
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
/**
* 3. 为channel通道绑定监听端口
*/
serverSocketChannel.bind(new InetSocketAddress(8000));
/**
* 4. **设置channel为非阻塞模式**
*/
serverSocketChannel.configureBlocking(false);
/**
* 5. 将channel注册到selector上,监听连接事件
*/
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务器启动成功!");
/**
* 6. 循环等待新接入的连接
*/
for (;;) { // while(true) c for;;
/**
* TODO 获取可用channel数量
*/
int readyChannels = selector.select();
/**
* TODO 为什么要这样!!?
*/
if (readyChannels == 0) continue;
/**
* 获取可用channel的集合
*/
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
/**
* selectionKey实例
*/
SelectionKey selectionKey = (SelectionKey) iterator.next();
/**
* **移除Set中的当前selectionKey**
*/
iterator.remove();
/**
* 7. 根据就绪状态,调用对应方法处理业务逻辑
*/
/**
* 如果是 接入事件
*/
if (selectionKey.isAcceptable()) {
acceptHandler(serverSocketChannel, selector);
}
/**
* 如果是 可读事件
*/
if (selectionKey.isReadable()) {
readHandler(selectionKey, selector);
}
}
}
}
/**
* 接入事件处理器
*/
private void acceptHandler(ServerSocketChannel serverSocketChannel,
Selector selector)
throws IOException {
/**
* 如果要是接入事件,创建socketChannel
*/
SocketChannel socketChannel = serverSocketChannel.accept();
/**
* 将socketChannel设置为非阻塞工作模式
*/
socketChannel.configureBlocking(false);
/**
* 将channel注册到selector上,监听 可读事件
*/
socketChannel.register(selector, SelectionKey.OP_READ);
/**
* 回复客户端提示信息
*/
socketChannel.write(Charset.forName("UTF-8")
.encode("你与聊天室里其他人都不是朋友关系,请注意隐私安全"));
}
/**
* 可读事件处理器
*/
private void readHandler(SelectionKey selectionKey, Selector selector)
throws IOException {
/**
* 要从 selectionKey 中获取到已经就绪的channel
*/
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
/**
* 创建buffer
*/
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
/**
* 循环读取客户端请求信息
*/
String request = "";
while (socketChannel.read(byteBuffer) > 0) {
/**
* 切换buffer为读模式
*/
byteBuffer.flip();
/**
* 读取buffer中的内容
*/
request += Charset.forName("UTF-8").decode(byteBuffer);
}
/**
* 将channel再次注册到selector上,监听他的可读事件
*/
socketChannel.register(selector, SelectionKey.OP_READ);
/**
* 将客户端发送的请求信息 广播给其他客户端
*/
if (request.length() > 0) {
// 广播给其他客户端
broadCast(selector, socketChannel, request);
}
}
/**
* 广播给其他客户端
*/
private void broadCast(Selector selector,
SocketChannel sourceChannel, String request) {
/**
* 获取到所有已接入的客户端channel
*/
Set<SelectionKey> selectionKeySet = selector.keys();
/**
* 循环向所有channel广播信息
*/
selectionKeySet.forEach(selectionKey -> {
Channel targetChannel = selectionKey.channel();
// 剔除发消息的客户端
if (targetChannel instanceof SocketChannel
&& targetChannel != sourceChannel) {
try {
// 将信息发送到targetChannel客户端
((SocketChannel) targetChannel).write(
Charset.forName("UTF-8").encode(request));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* 主方法
* @param args
*/
public static void main(String[] args) throws IOException {
new NioServer().start();
}
}
NIO客户端
public class NioClient {
/**
* 启动
*/
public void start(String nickname) throws IOException {
/**
* 连接服务器端
*/
SocketChannel socketChannel = SocketChannel.open(
new InetSocketAddress("127.0.0.1", 8000));
/**
* 接收服务器端响应
*/
// 新开线程,专门负责来接收服务器端的响应数据
// selector , socketChannel , 注册
Selector selector = Selector.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
new Thread(new NioClientHandler(selector)).start();
/**
* 向服务器端发送数据
*/
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String request = scanner.nextLine();
if (request != null && request.length() > 0) {
socketChannel.write(
Charset.forName("UTF-8")
.encode(nickname + " : " + request));
}
}
}
public static void main(String[] args) throws IOException {
// new NioClient().start();
}
}
客户端线程,处理服务器端响应的的消息
public class NioClientHandler implements Runnable {
private Selector selector;
public NioClientHandler(Selector selector) {
this.selector = selector;
}
@Override
public void run() {
try {
for (;;) {
int readyChannels = selector.select();
if (readyChannels == 0) continue;
/**
* 获取可用channel的集合
*/
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
/**
* selectionKey实例
*/
SelectionKey selectionKey = (SelectionKey) iterator.next();
/**
* **移除Set中的当前selectionKey**
*/
iterator.remove();
/**
* 7. 根据就绪状态,调用对应方法处理业务逻辑
*/
/**
* 如果是 可读事件
*/
if (selectionKey.isReadable()) {
readHandler(selectionKey, selector);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 可读事件处理器
*/
private void readHandler(SelectionKey selectionKey, Selector selector)
throws IOException {
/**
* 要从 selectionKey 中获取到已经就绪的channel
*/
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
/**
* 创建buffer
*/
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
/**
* 循环读取服务器端响应信息
*/
String response = "";
while (socketChannel.read(byteBuffer) > 0) {
/**
* 切换buffer为读模式
*/
byteBuffer.flip();
/**
* 读取buffer中的内容
*/
response += Charset.forName("UTF-8").decode(byteBuffer);
}
/**
* 将channel再次注册到selector上,监听他的可读事件
*/
socketChannel.register(selector, SelectionKey.OP_READ);
/**
* 将服务器端响应信息打印到本地
*/
if (response.length() > 0) {
System.out.println(response);
}
}
}
我们定义三个客户端,模拟三个用户在聊天室发送消息
public class AClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("AClient");
}
}
public class BClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("BClient");
}
}
public class CClient {
public static void main(String[] args)
throws IOException {
new NioClient().start("CClient");
}
}
NIO 聊天室到此结束
来源:https://blog.csdn.net/sinat_36899414/article/details/106169245


猜你喜欢
- 什么是mybatisMyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数
- 骑士周游问题在8x8的国际棋盘上,按照马走日的规则,验证是否能够走遍棋盘。解题思路1、创建棋盘 chessBoard,是一个二维数组。2、将
- 在C#中数组Array,ArrayList,泛型List都能够存储一组对象,但是在开发中根本不知道用哪个性能最高,下面我们慢慢分析分析。一、
- 1 什么是条件变量condition_variable是一个类,常和mutex搭配使用。condition_variable类是一个同步原语
- 现在的应用在注册登录或者修改密码中都用到了短信验证码,那在android中是如何实现获取短信验证码并自动填写的呢?首先,需要要在manife
- 软件需求VS2019社区版、win10操作系统、opencv4.1.0VS2019社区版(免费) 下载地址OpenCV4.1.0 下载地址配
- 在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择。这些功能我们叫它Android Di
- 用C#如何生成二维码,我们可以通过现有的第三方dll直接来实现,下面列出几种不同的生成方法:1):通过QrCodeNet(Gma.QrCod
- LeetCode54. 螺旋矩阵 java实现题目难度 中给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,
- 本文实例为大家分享了C语言实现生日贺卡的具体代码,供大家参考,具体内容如下//********** 编译环境VC6.0 **********
- 一、模拟业务需求假设我们现在需要在我们的系统中导入一批关于学生信息的Excel的数据,其主要的信息有:学号、姓名、年龄、性别等等,在导入系统
- 大致流程客户端根据远程服务的地址,客户端发送请求至服务端,服务端解析信息并找到对应的实现类,进行方法调用,之后将调用结果原路返回,客户端解析
- 真正的帮助大家理解红黑树:一、红黑树所处数据结构的位置:在JDK源码中, 有treeMap和JDK8的HashMap都用到了红黑树去存储红黑
- android中定时有很多种是实现,常见的Handler 与Thread的结合,handler.postDelayed ,以及要使用的Ala
- 本文实例为大家分享了java实现随机数生成器的具体代码,供大家参考,具体内容如下自己编的随机数生成器,比较简陋,功能也单一,当作练手。App
- 本文为大家分享了C#实现窗体全屏的具体代码,供大家参考,具体内容如下方法一:不过此方法有时候会出现莫名的bug//程序启动路径,与生成程序的
- Java基础 Servlet * 详解 1 概念:Servlet * ,用来监听web容器的一些对象状态的变化,主要是Servle
- 微信登录的实现与qq登录类似。不过微信登录比较麻烦,需要拿到开发者资质认证,花300块钱,然后应用的话还得有官网之类的,就是比较繁琐的前期准
- 1,带Tomcat的打包方式1.1, 在pom.xml文件添加以下配置(目的:自定main入口和跳过Junit代码)<build>
- 示例 1 :使用搜索表单创建全屏模式我们要构建的小应用程序有一个应用程序栏,右侧有一个搜索按钮。按下此按钮时,将出现一个全屏模式对话框。它不