struct模块解决黏包

https://blog.csdn.net/u013193903/article/details/80739249 struct模块

判断数据大小来解决黏包

mport socket
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn,addr = sk.accept()
while True:
    cmd=input('>>>>>>')
    if cmd=='q':
        conn.send(b'q')
        break
    conn.send(cmd.encode('gbk'))
    num=conn.recv(1024).decode('utf-8')#因为解码
    conn.send(b'ok')
    res=conn.recv(int(num)).decode('gbk')#需要解码
    print(res)


conn.close()
sk.close()

conn.close()
sk.close()


#client

#client
import socket
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8090))
while True:
    cmd = sk.recv(1024).decode('gbk')#因为是bytes类型所以需要解码
    if cmd=='q':
        break
    res = subprocess.Popen(cmd,shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    std_out=res.stdout.read()#管道读取只能一次
    std_err=res.stderr.read()#管道读取只能一次
    sk.send(str(len(std_err)+len(std_out)).encode('utf-8'))
    sk.recv(1024)
    sk.send(std_out)#因为之前已经读取了
    sk.send(std_err)#因为之前已经读取了
sk.close()

struct解决黏包

#client
import socket,struct
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8090))
while True:
    cmd = sk.recv(1024).decode('gbk')#因为是bytes类型所以需要解码
    if cmd=='q':
        break
    res = subprocess.Popen(cmd,shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    std_out=res.stdout.read()#管道读取只能一次
    std_err=res.stderr.read()#管道读取只能一次
    # sk.send(str(len(std_err) + len(std_out)).encode('utf-8'))
    # sk.recv(1024)
    len_num=len(std_err)+len(std_out)
    # print(type(std_err))
    # print(len_num)调试
    num_by=struct.pack('i',len_num)
    sk.send(num_by)
    sk.send(std_out)#因为之前已经读取了
    sk.send(std_err)#因为之前已经读取了
sk.close()```


#sever

import socket,struct
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn,addr = sk.accept()
while True:
    cmd=input('>>>>>>')
    if cmd=='q':
        conn.send(b'q')
        break


    conn.send(cmd.encode('gbk'))
    # num = conn.recv(1024).decode('utf-8')  # 因为解码
    # conn.send(b'ok')
    num=conn.recv(4)
    num=struct.unpack('i',num)[0]
    res=conn.recv(int(num)).decode('gbk')#需要解码
    print(res)


conn.close()
sk.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值