当前位置: 首页 > news >正文

NIO的callback调用方式

1.消费者

public class CallbackClient {public static void main(String[] args) {try {SocketChannel socketChannel = SocketChannel.open();socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));ByteBuffer writeBuffer = ByteBuffer.allocate(32);ByteBuffer readBuffer = ByteBuffer.allocate(32);getMessage(readBuffer, socketChannel);sendRandomInt(writeBuffer, socketChannel, 1000);getMessage(readBuffer, socketChannel);try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}sendRandomInt(writeBuffer, socketChannel, 10);getMessage(readBuffer, socketChannel);socketChannel.close();} catch (IOException e) {}}public static void sendRandomInt(ByteBuffer writeBuffer, SocketChannel socketChannel, int bound) {Random r = new Random();int d = 0;d = r.nextInt(bound);if (d == 0)d = 1;System.out.println(d);writeBuffer.clear();writeBuffer.put(String.valueOf(d).getBytes());writeBuffer.flip();try {socketChannel.write(writeBuffer);} catch (IOException e) {e.printStackTrace();}}public static void getMessage(ByteBuffer readBuffer, SocketChannel socketChannel) {readBuffer.clear();byte[] buf = new byte[16];try {socketChannel.read(readBuffer);} catch (IOException e) {}readBuffer.flip();readBuffer.get(buf, 0, readBuffer.remaining());System.out.println(new String(buf));}
}

2.服务提供者

package com.example.demo.callback;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;public class NioServer {public static void main(String[] args) throws IOException {// 打开服务器套接字通道ServerSocketChannel serverSocket = ServerSocketChannel.open();serverSocket.configureBlocking(false);serverSocket.socket().bind(new InetSocketAddress(8000));// 打开多路复用器Selector selector = Selector.open();// 注册服务器通道到多路复用器上,并监听接入事件serverSocket.register(selector, SelectionKey.OP_ACCEPT);final ByteBuffer buffer = ByteBuffer.allocate(1024);while (true) {// 非阻塞地等待注册的通道事件selector.select();// 获取发生事件的selectionKey集合Set<SelectionKey> selectedKeys = selector.selectedKeys();Iterator<SelectionKey> it = selectedKeys.iterator();// 遍历所有发生事件的selectionKeywhile (it.hasNext()) {SelectionKey key = it.next();it.remove();// 处理接入请求if (key.isAcceptable()) {ServerSocketChannel ssc = (ServerSocketChannel) key.channel();SocketChannel socketChannel = ssc.accept();socketChannel.configureBlocking(false);SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_WRITE, ByteBuffer.allocate(1024));//添加后可使用处理方法2处理CommonClient client = new CommonClient(socketChannel, newKey);newKey.attach(client);}// 处理读事件if (key.isReadable()) {SocketChannel socketChannel = (SocketChannel) key.channel();buffer.clear();while (socketChannel.read(buffer) > 0) {buffer.flip();String receivedMessage = StandardCharsets.UTF_8.decode(buffer).toString();handleReceivedMessage(socketChannel, receivedMessage);buffer.clear();}//处理方法2CommonClient client = (CommonClient) key.attachment();client.onRead();}// 处理写事件if (key.isWritable()) {//处理方法1可以仿照方法2的格式写//处理方法2CommonClient client = (CommonClient) key.attachment();client.onWrite();}}}}// 回调函数,处理接收到的数据private static void handleReceivedMessage(SocketChannel socketChannel, String message) throws IOException {System.out.println("Received message: " + message);// 回复客户端socketChannel.write(ByteBuffer.wrap("Server received the message".getBytes(StandardCharsets.UTF_8)));}
}
public class CommonClient {private SocketChannel clientSocket;private ByteBuffer recvBuffer;private SelectionKey key;private Callback callback;private String msg;public CommonClient(SocketChannel clientSocket, SelectionKey key) {this.clientSocket = clientSocket;this.key = key;recvBuffer = ByteBuffer.allocate(8);try {this.clientSocket.configureBlocking(false);key.interestOps(SelectionKey.OP_WRITE);} catch (IOException e) {}}public void close() {try {clientSocket.close();key.cancel();}catch (IOException e){};}// an rpc to notify client to send a numberpublic void sendMessage(String msg, Callback cback)  {this.callback = cback;try {try {recvBuffer.clear();recvBuffer.put(msg.getBytes());recvBuffer.flip();clientSocket.write(recvBuffer);key.interestOps(SelectionKey.OP_READ);} catch (IOException e) {e.printStackTrace();}}catch (Exception e) {}}// when key is writable, resume the fiber to continue// to write.public void onWrite() {sendMessage("divident", new Callback() {@Overridepublic void onSucceed(int data) {int a = data;sendMessage("divisor", new Callback() {@Overridepublic void onSucceed(int data) {int b = data;sendMessage(String.valueOf(a / b), null);}});}});}public void onRead() {int res = 0;try {try {recvBuffer.clear();// read may fail even SelectionKey is readable// when read fails, the fiber should suspend, waiting for next// time the key is ready.int n = clientSocket.read(recvBuffer);while (n == 0) {n = clientSocket.read(recvBuffer);}if (n == -1) {close();return;}System.out.println("received " + n + " bytes from client");} catch (IOException e) {e.printStackTrace();}recvBuffer.flip();res = getInt(recvBuffer);// when read ends, we are no longer interested in reading,// but in writing.key.interestOps(SelectionKey.OP_WRITE);} catch (Exception e) {}this.callback.onSucceed(res);}public int getInt(ByteBuffer buf) {int r = 0;while (buf.hasRemaining()) {r *= 10;r += buf.get() - '0';}return r;}}
    public interface Callback {public void onSucceed(int data);}

相关文章:

NIO的callback调用方式

1.消费者 public class CallbackClient {public static void main(String[] args) {try {SocketChannel socketChannel SocketChannel.open();socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));ByteBuffer writeBuffer ByteBuffer.allocate(32);…...

百度文心智能体平台开发萌猫科研加油喵

百度文心智能体平台开发萌猫科研加油喵 在科研的道路上&#xff0c;研究生们常常面临着巨大的压力和挑战。为了给这个充满挑战的群体带来一些鼓励和温暖&#xff0c;我借助百度文心智能体平台开发了一个独特的智能体 《萌猫科研加油喵》。 一、百度文心智能体平台介绍 百度文…...

Hive数仓操作(十六)

DML&#xff08;数据操作语言&#xff09;指的是用于操作数据的 SQL 语言部分&#xff0c;主要包括对数据的插入、更新、删除等操作。Hive 的 DML语句主要包括 INSERT、UPDATE 和 DELETE 。以下是一些重要的 Hive DML 语句及其解析。 Hive的DML语句 一、 插入操作INSERT 一般…...

第十二届蓝桥杯嵌入式省赛程序设计题解析(基于HAL库)(第一套)

一.题目分析 &#xff08;1&#xff09;.题目 &#xff08;2&#xff09;.题目分析 1.串口功能分析 a.串口接收车辆出入信息&#xff1a;通过查询车库的车判断车辆是进入/出去 b.串口输出计费信息&#xff1a;输出编号&#xff0c;时长和费用 c.计算停车时长是难点&#x…...

MongoDB入门:安装及环境变量配置

一、安装MonggoDB Windows系统安装MongoDB 1、下载MongoDB安装包 访问MongoDB官方网站&#xff0c;选择与Windows系统相匹配的MongoDB Community Server版本进行下载。 Download MongoDB Community Server | MongoDB 2、安装MongoDB 双击下载好的安装包文件&#xff0c;根…...

利用 notepad++ 初步净化 HaE Linkfinder 规则所提取的内容(仅留下接口行)

去掉接口的带参部分 \?.*去掉文件行 .*\.(docx|doc|xlsx|xls|txt|xml|html|pdf|ppt|pptx|odt|ods|odp|rtf|md|epub|css|scss|less|sass|styl|png|jpg|jpeg|gif|svg|ico|bmp|tiff|webp|heic|dds|raw|vue|js|ts|mp4|avi|mov|wmv|mkv|flv|webm|mp3|wav|aac|flac|ogg|m4a).*(\r\…...

RCE(remote command/code execute)远程命令注入

远程命令注入RCE RCE(remote command/code execute&#xff0c;远程命令执行)漏洞&#xff0c;一般出现这种漏洞&#xff0c;是因为应用系统从设计上需要给用户提供指定的远程命令操作的接口&#xff0c;比如我们常见的路由器、防火墙、入侵检测等设备的web管理界面上。一般会给…...

​一篇关于密码学的概念性文章

文章目录 1. 引言2. 加密学基本概念3. 加密算法的类型3.1 对称密钥加密(SKC)3.2 公钥密码学3.3 哈希函数3.4. 为什么需要三种加密技术?3.5 密钥长度的重要性4. 信任模型4.1 PGP信任网络4.2 Kerberos4.3 公钥证书和证书颁发机构4.4 总结5. 密码算法的实际应用5.1 密码保护5.2…...

什么是汽车中的SDK?

无论是在家里使用预制菜包做一顿大厨级别的晚餐&#xff0c;还是使用IKEA套组装配出时尚的北欧风桌子&#xff0c;我们都熟悉这样一种概念&#xff1a;比起完全从零开始&#xff0c;使用工具包可以帮助我们更快、更高效地完成一件事。 在速度至关重要的商业软件领域&#xff0…...

利用CRITIC客观权重赋权法进行数值评分计算——算法过程

1、概述 ‌CRITIC客观评价法是一种基于指标的对比强度和指标之间的冲突性来确定指标客观权数的方法。‌ 该方法适用于判断数据稳定性&#xff0c;并且适合分析指标或因素之间有着一定的关联的数据‌。 CRITIC方法的基本原理包括两个主要概念&#xff1a;对比强度和指标之间的…...

一个月学会Java 第4天 运算符和数据转换

Day4 运算符和数据转换 今天来讲运算符&#xff0c;每个运算符的作用和现象&#xff0c;首先我们先复习一下数据类型&#xff0c; day2讲过基本数据类型有八种&#xff0c;int、short、long、byte、char、boolean、float、double&#xff0c;分别为四个整型、一个字符型、一个布…...

Stream流的终结方法(一)

1.Stream流的终结方法 2.forEach 对于forEach方法&#xff0c;用来遍历stream流中的所有数据 package com.njau.d10_my_stream;import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.function.Consumer; import java.util…...

GO网络编程(二):客户端与服务端通信【重要】

本节是新知识&#xff0c;偏应用&#xff0c;需要反复练习才能掌握。 目录 1.C/S通信示意图2.服务端通信3.客户端通信4.通信测试5.进阶练习&#xff1a;客户端之间通信 1.C/S通信示意图 客户端与服务端通信的模式也称作C/S模式&#xff0c;流程图如下 其中P是协程调度器。可…...

快速熟悉Nginx

一、Nginx是什么&#xff1f; ‌Nginx是一款高性能、轻量级的Web服务器和反向代理服务器。‌ ‌特点‌&#xff1a;Nginx采用事件驱动的异步非阻塞处理框架&#xff0c;内存占用少&#xff0c;并发能力强&#xff0c;资源消耗低。‌功能‌&#xff1a;Nginx主要用作静态文件服…...

VikParuchuri/marker 学习简单总结

核心代码 VikParuchuri/marker 的核心是使用https://github.com/VikParuchuri/surya的 pdf 模型,注意不仅仅是ocr,在marker的代码里面有标注ocr 是option的。强制OCR 要设置:OCR_ALL_PAGES=true核心代码就是convert.py def convert_single_pdf(fname: str,model_lst: List,…...

【AI知识点】词嵌入(Word Embedding)

词嵌入&#xff08;Word Embedding&#xff09;是自然语言处理&#xff08;NLP&#xff09;中的一种技术&#xff0c;用于将词语或短语映射为具有固定维度的实数向量。这些向量&#xff08;嵌入向量&#xff09;能够捕捉词语之间的语义相似性&#xff0c;即将语义相近的词映射到…...

Python从入门到高手5.1节-Python简单数据类型

目录 5.1.1 理解数据类型 5.1.2 Python中的数据类型 5.1.3 Python简单数据类型 5.1.4 特殊的空类型 5.1.5 Python变量的类型 5.1.6 广州又开始变热 5.1.1 理解数据类型 数据类型是根据数据本身的性质和特征来对数据进行分类&#xff0c;例如奇数与偶数就是一种数据类型。…...

Hbase要点简记

Hbase要点简记 Hbase1、底层架构2、表逻辑结构 Hbase HBase是一个分布式的、列式的、实时查询的、非关系型数据库&#xff0c;可以处理PB级别的数据&#xff0c;吞吐量可以到的百万查询/每秒。主要应用于接口等实时数据应用需求&#xff0c;针对具体需求&#xff0c;设计高效率…...

RabbitMQ的各类工作模式介绍

简单模式 P: ⽣产者, 也就是要发送消息的程序 C: 消费者,消息的接收者 Queue: 消息队列, 图中⻩⾊背景部分. 类似⼀个邮箱, 可以缓存消息; ⽣产者向其中投递消息, 消费者从其中取出消息.特点: ⼀个⽣产者P&#xff0c;⼀个消费者C, 消息只能被消费⼀次. 也称为点对点(Point-to-…...

李宏毅深度学习-图神经网络GNN

图卷积的开源代码网站DGL 好用的还是 GAT, GIN&#xff08;指出最好的卷积 就是 hi 邻居特征&#xff08;而且只能用 sum&#xff09;&#xff09; Introduction GNN 可以理解为是由 Graph&#xff08;图) Nerual Networks 组合而成的&#xff0c;图结构应该都在数据结构与…...

零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?

一、核心优势&#xff1a;专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发&#xff0c;是一款收费低廉但功能全面的Windows NAS工具&#xff0c;主打“无学习成本部署” 。与其他NAS软件相比&#xff0c;其优势在于&#xff1a; 无需硬件改造&#xff1a;将任意W…...

Leetcode 3576. Transform Array to All Equal Elements

Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接&#xff1a;3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到&#xf…...

椭圆曲线密码学(ECC)

一、ECC算法概述 椭圆曲线密码学&#xff08;Elliptic Curve Cryptography&#xff09;是基于椭圆曲线数学理论的公钥密码系统&#xff0c;由Neal Koblitz和Victor Miller在1985年独立提出。相比RSA&#xff0c;ECC在相同安全强度下密钥更短&#xff08;256位ECC ≈ 3072位RSA…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

连锁超市冷库节能解决方案:如何实现超市降本增效

在连锁超市冷库运营中&#xff0c;高能耗、设备损耗快、人工管理低效等问题长期困扰企业。御控冷库节能解决方案通过智能控制化霜、按需化霜、实时监控、故障诊断、自动预警、远程控制开关六大核心技术&#xff0c;实现年省电费15%-60%&#xff0c;且不改动原有装备、安装快捷、…...

腾讯云V3签名

想要接入腾讯云的Api&#xff0c;必然先按其文档计算出所要求的签名。 之前也调用过腾讯云的接口&#xff0c;但总是卡在签名这一步&#xff0c;最后放弃选择SDK&#xff0c;这次终于自己代码实现。 可能腾讯云翻新了接口文档&#xff0c;现在阅读起来&#xff0c;清晰了很多&…...

解决:Android studio 编译后报错\app\src\main\cpp\CMakeLists.txt‘ to exist

现象&#xff1a; android studio报错&#xff1a; [CXX1409] D:\GitLab\xxxxx\app.cxx\Debug\3f3w4y1i\arm64-v8a\android_gradle_build.json : expected buildFiles file ‘D:\GitLab\xxxxx\app\src\main\cpp\CMakeLists.txt’ to exist 解决&#xff1a; 不要动CMakeLists.…...

手机平板能效生态设计指令EU 2023/1670标准解读

手机平板能效生态设计指令EU 2023/1670标准解读 以下是针对欧盟《手机和平板电脑生态设计法规》(EU) 2023/1670 的核心解读&#xff0c;综合法规核心要求、最新修正及企业合规要点&#xff1a; 一、法规背景与目标 生效与强制时间 发布于2023年8月31日&#xff08;OJ公报&…...

关于easyexcel动态下拉选问题处理

前些日子突然碰到一个问题&#xff0c;说是客户的导入文件模版想支持部分导入内容的下拉选&#xff0c;于是我就找了easyexcel官网寻找解决方案&#xff0c;并没有找到合适的方案&#xff0c;没办法只能自己动手并分享出来&#xff0c;针对Java生成Excel下拉菜单时因选项过多导…...

《Docker》架构

文章目录 架构模式单机架构应用数据分离架构应用服务器集群架构读写分离/主从分离架构冷热分离架构垂直分库架构微服务架构容器编排架构什么是容器&#xff0c;docker&#xff0c;镜像&#xff0c;k8s 架构模式 单机架构 单机架构其实就是应用服务器和单机服务器都部署在同一…...