目錄json
serversocket
import socket import struct service=socket.socket() service.bind(('127.0.0.1',8081)) while True: service.listen(5) conn,address=service.accept() print('有客戶端鏈接進來了,地址以下',address) #獲取頭的內容 dic_len_byte=conn.recv(4) print(dic_len_byte) dic_len=struct.unpack('i',dic_len_byte)[0] print(dic_len) dic_head=eval(conn.recv(dic_len)) data=conn.recv(dic_head['size']) data_name=dic_head['name'] # print(data.decode('utf8')) with open(data_name,'wb') as fw: fw.write(data)
client測試
import socket import struct client=socket.socket() client.connect(('127.0.0.1', 8081)) import os import json print(os.path.getsize('test.py')) data_head={'size':os.path.getsize('test.py'),'name':'test_new.py'} data_head_s=json.dumps(data_head) data_head_bytes=data_head_s.encode('utf8') print(data_head_bytes) #把頭的長度以長度爲4的字節發送過去 head_len_bytes=struct.pack('i',len(data_head_bytes)) client.send(head_len_bytes) client.send(data_head_bytes) with open('test.py','rb') as fr: data=fr.read() client.send(data)
測試文件code
import json ss={'name':'ypp','age':False} data=json.dumps(ss) #轉json字典爲字符串(json格式) print(data) print(type(data)) data1=json.loads(data)#字符串的json格式的字典 轉爲字典 print(data1) print(type(data1)) sss=b'kkk\n\nkk' print(str(sss.decode('utf8')))