import struct
print(int.to_bytes(1534,2,byteorder='little')) #把整数转化为2个字节
#b'\xfe\x05'
print(int.from_bytes(b'\xfe\x05',byteorder='little')) #把字节转化为整数
# 1534
a=bool.to_bytes(True,1,byteorder='little') #后面1表1个字节
print(a)
# b'\x01'
b=bool.from_bytes(b'\x01',byteorder='little')
print(b)
# True
#########################################################################
#用struck
l= struct.pack('<i',1534) #占用4个字节
print(l)
# b'\xfe\x05\x00\x00'
data=struct.unpack('<i',b'\xfe\x05\x00\x00')[0] #返回以元组方式
print(data)
q=struct.pack('?',True)
print(q)
# b'\x01'
p=struct.unpack('?',b'\x01')[0]
print(p)
# True
f=struct.pack('<f',10.2)
print(f)
# b'33#A'
print(struct.unpack('<f',b'33#A')[0])
# 10.199999809265137
####################################################
h='hello python'.encode('utf-8')
print(h)
# b'hello python'
print(b'hello python'.decode('utf-8'))
# hello python
from socket import socket,SOCK_STREAM,AF_INET
from base64 import b64encode
from threading import Thread
import json
def main():
class FileTrans(Thread):
def __init__(self, parent):
super(FileTrans, self).__init__()
self.parent = parent
def run(self):
my_dict = {}
my_dict['filename'] = "guguo.jpg"
my_dict['filedata'] = data
json_str = json.dumps(my_dict)
self.parent.send(json_str.encode('utf-8'))
self.parent.close()
#创建服务端
server= socket()
server.bind(("127.0.0.1",8222))
server.listen(512)
print('-'*100)
with open("./bg6.jpg",'rb')as f:
#图片是二进制
data = b64encode(f.read()).decode('utf-8')
# print(data)
while True:
client,addr = server.accept()
#开启
FileTrans(client).start()
if __name__ == '__main__':
main()
from socket import socket,AF_INET,SOCK_STREAM
import json
from base64 import b64decode
def main():
client = socket()
client.connect(('127.0.0.1',8222))
in_data = bytes()
data=client.recv(1024)
while data:
in_data+=data
data=client.recv(1024)
print("接受服务端数据",in_data)
my_dict = json.loads(in_data.decode('utf-8'))
filename = my_dict['filename']
file_data = my_dict['filedata'].encode('utf-8')
with open('./'+filename,'wb')as f:
f.write(b64decode(file_data))
print('保存成功')
if __name__ == '__main__':
main()