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

C#处理网络传输中不完整的数据流

1、背景

在读取byte数组的场景(例如:读取文件、网络传输数据)中,特别是网络传输的场景中,非常有可能接收了不完整的byte数组,在将byte数组转换时,因字符的缺失/增多,转为乱码。如下图所示

在这里插入图片描述

2、具体实现

在C#中有Decoder可供使用,其内部有换存(buffer),可以现将非完整的byte存储起来,等到后新的数据后,再拼接起来,形成完成的内容。具体代码及说明如下:

// See https://aka.ms/new-console-template for more information
using System.ComponentModel;
using System.Text;//初始化的字符串
string helloStr = "你好Ha";
Console.WriteLine(helloStr);byte[] helloArray=Encoding.UTF8.GetBytes(helloStr);
Console.WriteLine("你好Ha对应的byte数组内容(十六进制):" + BitConverter.ToString(helloArray));ArraySegment<byte> helloSegment= new ArraySegment<byte>(helloArray,0,4);
Console.WriteLine("若网络传输中先收到了前4个:"+BitConverter.ToString(helloSegment.ToArray()));
Console.WriteLine("转换为string会发现结果是不对的:"+Encoding.UTF8.GetString(helloSegment));Console.WriteLine("下面是使用GetDecoder方法进行处理");
Decoder dncoder = Encoding.UTF8.GetDecoder();int charCount= dncoder.GetCharCount(helloSegment, false);
Console.WriteLine("还是同样的前4个,判断收到了几个【完整】的字符:"+charCount);Console.WriteLine("将前3位,加载到halfCharArray数组中");
char[] halfCharArray = new char[charCount];
dncoder.GetChars(helloSegment.ToArray(), 0, helloSegment.Count, halfCharArray, 0);Console.WriteLine("解析完的字符是:"+ new string(halfCharArray));ArraySegment<byte> otherHalfStr = new ArraySegment<byte>(helloArray, 4, 4);
Console.WriteLine("若网络传输中先收到了后4个:" + BitConverter.ToString(otherHalfStr.ToArray()));//继续转换
//若能判断,本次接受的数据为最终的数据,则GetCharCount的第二个参数,应当设置为true,(强制清空Buffer,避免后续使用时影响后续的解析)
int otherCharCount = dncoder.GetCharCount(otherHalfStr, true);  
Console.WriteLine("缓存+新接受的字符数量:" + otherCharCount);
char[] ohterHalfCharArray = new char[otherCharCount];
dncoder.GetChars(otherHalfStr.ToArray(), 0, otherHalfStr.Count, ohterHalfCharArray, 0);
Console.WriteLine("解析完的字符是:" + new string(ohterHalfCharArray));Console.Read();

以上代码运行后的结果,如图所示:
在这里插入图片描述

3、参考

官网的参考资料

http://www.xdnf.cn/news/64531.html

相关文章:

  • Maxscript调用Newtonsoft.Json解析Json
  • 制作一款打飞机游戏13:状态机
  • 广州可信数据空间上线:1个城市枢纽+N个产业专区+高质量数据集(附28个数据集清单)
  • 如何建设企业级合成数据中台?架构设计、权限治理与复用机制全解
  • 第 3 篇:揭秘时间模式 - 时间序列分解
  • OpenCV基础函数学习4
  • 【油藏地球物理正演软件ColchisFM】ColchisFM正演软件在阿姆河右岸区块礁滩复合体识别中的应用
  • transformer
  • 【Docker-16】Docker Volume存储卷
  • android 多个viewmodel之间通信
  • Android 最简单的native二进制程序
  • 【MySQL】:数据库事务管理
  • 深入理解路由器、IP地址及网络配置
  • 你的大模型服务如何压测:首 Token 延迟、并发与 QPS
  • 前端笔记-AJAX
  • Excel/WPS表格中图片链接转换成对应的实际图片
  • 大模型应用开发大纲
  • 前端框架开发编译阶段与运行时的核心内容详解Tree Shaking核心实现原理详解
  • C语言中的双链表和单链表详细解释与实现
  • PostgreSQL 用户资源管理
  • 基于LLM的响应式流式处理实践:提升用户体验的关键技术
  • 【python】copy deepcopy 赋值= 对比
  • el-input 限制只能输入非负数字和小数
  • 基于SIMMECHANICS的单自由度磁悬浮隔振器PID控制系统simulink建模与仿真
  • linux基础学习--linux文件与目录管理
  • 【python实用小脚本系列】用Python打造你的专属智能语音助手
  • 【技术派后端篇】技术派中基于 Redis 的缓存实践
  • 快手砍掉本地生活的门槛
  • Redis的使用总结
  • 电脑硬盘常见的几种接口类型