第70天python学习TCP粘包解决方案struct模块

接下来我们先来介绍下可以解决黏包的模块的用法:

struct

python中的struct模块就提供了这样的机制,该模块的主要作用就是对python基本类型值与用python字符串格式表示的C struct类型间的转化(This module performs conversions between Python values and C structs represented as Python strings.)。stuct模块提供了很简单的几个函数,下面写例子。

两个函数:pack()、unpack()

struct模块最重要的两个函数就是pack()unpack()方法

打包函数:pack(fmt, v1, v2, v3, ...)

解包函数:unpack(fmt, buffer)

 

import struct
# pack 把任意长度的数字转化成固定4个字节长度的字节流
# unpack 将4个字节的值恢复成原本的数据,最后返回一个元组

res = struct.pack("i",2372722) #不能超过int 范围
print(res)
print(len(res))

res = struct.unpack("i",res)
print(res)
print(res[0],type(res[0]))

猜你喜欢

转载自www.cnblogs.com/jianchixuexu/p/11892650.html
今日推荐