简单的文件ftp上传
-
server
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)
-
测试文件
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 kk' print(str(sss.decode('utf8')))