python 用struct模块解决黏包问题
作者:手可摘星辰。 时间:2023-08-18 02:13:20
为什么会出现黏包现象:
首先只有在TCP协议中才会出现黏包现象,是因为TCP协议是面向流的协议,在发送的数据传输的过程中还有缓存机制来避免数据丢失,因此,在连续发送小数据的时候,以及接收大小不符的时候容易出现黏包现象。本质还是因为我们在接收数据的时候不知道发送的数据的长短。
解决黏包问题
在传输大量数据之前首先告诉接收端要发送的数据大小,如果想更漂亮的解决问题,可以通过struct模块来定制协议。
struct模块:
功能:可以把一个类型,如数字,转成固定长度的bytes。
import struct
ret = struct.pack('i',456872783) #'i'代表int,就是即将要把一共数字转换成固定长度(4个字节)的bystes类型
print(ret)
num = struct.unpack('i',ret) #转换回来,返回一个元组
print(num[0]) #提前元组中的值得到4096
解决黏包问题:
服务端:
import struct
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
conn,addr = sk.accept()
while True:
cmd = input('>>>')
if cmd == 'q': #当输入‘q'时,结束,并向客户端发送一个'q'。
conn.send(b'q')
break
conn.send(cmd.encode('gbk')) #将输入的cmd命令发送给客户端
num = conn.recv(4) #接收字节信息(返回的消息长度信息)。
num = struct.unpack('i',num)[0] #将接收的字节码转化为原来的类型并放在一个元组里面,后面加[0]是提前出元组中的值。
res = conn.recv(int(num)).decode('gbk') #接收长度为num 的消息。
print(res) #打印
conn.close()
sk.close()
客户端:
import struct
import socket
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
while True:
cmd = sk.recv(1024).decode('gbk') #接收服务端发送来的cmd命令
if cmd == 'q': #当接收到‘q'时,结束。
break
# 在客户端执行接收到的cmd命令。并将正确的消息和错误的消息分别放入stdout和stderr管道。
res = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
std_out = res.stdout.read() #读取管道内正确的消息
std_err = res.stderr.read() #读取管道内错误的消息
len_num = len(std_out)+len(std_err) #计算正确和错误消息的总长度
num_by = struct.pack('i',len_num) #将消息总长度转换成长度为4的字节码
sk.send(num_by) #发送消息长度信息
sk.send(std_out) #发送正确消息
sk.send(std_err) #发送错误消息
sk.close()
来源:https://www.cnblogs.com/wangdianchao/p/11698977.html
标签:python,struct,黏包
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python读取nc数据并绘图的方法实例
2023-09-16 10:08:19
![](https://img.aspxhome.com/file/2023/8/91868_0s.png)
重新编译PLSQL中的无效对象或者指定的对象 的方法
2009-02-26 10:41:00
python利用xpath爬取网上数据并存储到django模型中
2022-01-19 03:46:51
SQLServer中bigint转int带符号时报错问题解决方法
2024-01-16 00:13:01
phpmyadmin中禁止外网使用的方法
2023-09-12 01:10:22
case 嵌套查询与连接查询你需要懂得
2024-01-24 02:11:02
![](https://img.aspxhome.com/file/2023/8/96208_0s.png)
MySQLMerge存储引擎
2024-01-14 07:39:25
详解用selenium来下载小姐姐图片并保存
2023-08-11 02:02:31
![](https://img.aspxhome.com/file/2023/8/109588_0s.png)
python做反被爬保护的方法
2021-06-09 12:49:03
python日志logging模块使用方法分析
2023-01-06 17:22:51
![](https://img.aspxhome.com/file/2023/2/103802_0s.png)
thinkphp 多表 事务详解
2023-07-08 05:43:36
SqlServer查询和Kill进程死锁的语句
2024-01-23 11:07:42
Python爬虫入门案例之回车桌面壁纸网美女图片采集
2022-12-25 19:40:57
![](https://img.aspxhome.com/file/2023/9/133649_0s.png)
如何把Oracle 数据库从 RAC 集群迁移到单机环境
2024-01-28 06:29:05
Python基础教程之异常处理详解
2022-06-10 07:52:17
使用 Python 遍历目录树的方法
2021-09-21 22:19:32
js实现的全国省市二级联动下拉选择菜单完整实例
2023-09-09 05:21:01
![](https://img.aspxhome.com/file/2023/4/56304_0s.jpg)
vue.js 表格分页ajax 异步加载数据
2024-05-21 10:12:57
python数据爬下来保存的位置
2021-01-29 20:49:19
python实现雨滴下落到地面效果
2021-10-04 03:58:32
![](https://img.aspxhome.com/file/2023/4/101184_0s.gif)