提问人:lizayu 提问时间:11/7/2023 更新时间:11/7/2023 访问量:20
C# 网络数据流处理
C# network data stream processing
问:
当 C# 处理网络数据流时,数据流的编码通常不是固定的,并且可能是未知的。如果要替换数据流中英文字母的某一部分,例如删除数据流中的最后一个(0.02秒),使用C#需要通过已知的编码将网络数据流的bytes数组转换为字符串,然后使用常规或字符串函数进行处理。但正如刚才提到的,当 bytes 数组转换为字符串时,如果编码未知,就会发生错误。 Python3 基于字节类型编程。Python 在处理数据流时,不需要按照一定的编码将字节数据直接转换为字符串进行后处理。Python 的字符串函数可以直接对字节数据进行操作,而无需根据某种编码将字节转换为字符串,例如:
import re
# Assume that networkdata is a data packet obtained from the network, and the encoding in the data packet is unknown
# The requirement only needs to replace (0.02 secs). The ending English numeric characters
# Do not try to use decode or the like to convert a certain encoding into str type
networkdata = b"The data obtained from the Internet (0.02 secs).\r\n"
if networkdata.strip().endswith(b" (0.02 secs)."):
networkdata = re.sub(rb"\s\([0-9+.]+\ssecs\)\.\r\n$", b'\r\n', networkdata, 1)
print(networkdata) # Network data is sent out
上面的 python 可以在不知道编码的情况下直接对 bytes 类型轻松操作。我想问一下,当编码未知时,C#是否会在数据流上执行类似于上述python的操作?
我希望能够在C#中掌握此类问题的解决方案。
答: 暂无答案
评论