socket编程实现文件的上传和下载
Posted weidaijie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket编程实现文件的上传和下载相关的知识,希望对你有一定的参考价值。
server端
#!/usr/bin/env python # coding:utf-8 import socket import struct import json buffer = 1024 sk = socket.socket() sk.bind((‘127.0.0.1‘,8888)) sk.listen() conn,addr = sk.accept() ret = conn.recv(4) len_operate_c = struct.unpack(‘i‘,ret)[0] operate_c = conn.recv(len_operate_c) operate_c = operate_c.decode(‘utf-8‘) if operate_c == ‘upload‘: res = conn.recv(4) len_head = struct.unpack(‘i‘,res)[0] head = conn.recv(len_head).decode(‘utf-8‘) head = json.loads(head) filesize = head[‘filesize‘] filename = head[‘filename‘] with open (filename,‘wb‘) as f: while filesize: if filesize >= buffer: content = conn.recv(buffer) f.write(content) filesize -= buffer else : content = conn.recv(filesize) f.write(content) filesize = 0 conn.close() sk.close()
client端
#!/usr/bin/env python # coding:utf-8 def get_filename(file_path): return os.path.basename(file_path) import socket import os import json import struct buffer = 1024 sk = socket.socket() sk.connect((‘127.0.0.1‘,8888)) operate = [‘download‘,‘upload‘] for k,j in enumerate(operate,1) : print(k,j) num = int(input(‘请输入你的选项: ‘)) operate_c = operate[(num-1)] len_operate_c = len(operate_c) print(len_operate_c) res = struct.pack(‘i‘,len_operate_c) sk.send(res) sk.send(operate_c.encode(‘utf-8‘)) if operate_c == ‘upload‘ : head = {‘filename‘:None,‘filesize‘:None,} file_path = input("请输入要上传的文件绝对路径 :") filename = get_filename(file_path) head[‘filename‘] = filename filesize = os.path.getsize(file_path) head[‘filesize‘]=filesize json_head = json.dumps(head) len_head = len(json_head) ret = struct.pack(‘i‘,len_head) sk.send(ret) sk.send(json_head.encode(‘utf-8‘)) with open (file_path,‘rb‘) as f: while filesize: if filesize >= buffer : content = f.read(buffer) sk.send(content) filesize -= buffer else : content = f.read(filesize) sk.send(content) filesize = 0 sk.close()
以上是关于socket编程实现文件的上传和下载的主要内容,如果未能解决你的问题,请参考以下文章