码迷,mamicode.com
首页 > Web开发 > 详细

上传下载

时间:2018-09-17 22:10:57      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:hand   def   basename   发送   gif   info   luke   pen   upload   

技术分享图片
 1 import json
 2 import struct
 3 import socketserver
 4 import operate_handler
 5 class MyFTP(socketserver.BaseRequestHandler):
 6     def handle(self):
 7         conn = self.request
 8         length = conn.recv(4)
 9         length = struct.unpack(i,length)[0]
10         opertate = (conn.recv(length)).decode(utf-8)
11         opertate_dic = json.loads(opertate)
12         opt = opertate_dic[operate]
13         usr = opertate_dic[user]
14         print(opt,usr)
15         getattr(operate_handler,opt)(conn,usr)
16 
17 socketserver.TCPServer.allow_reuse_address = True
18 server = socketserver.ThreadingTCPServer((127.0.0.1,9000),MyFTP)
19 server.serve_forever()
server
技术分享图片
 1 import os
 2 import json
 3 import struct
 4 base_path = rD:\骑士计划PYTHON1期\day32\ftp\server\root
 5 
 6 def upload(conn,usr):
 7     fileinfo_len = conn.recv(4)
 8     fileinfo_len = struct.unpack(i,fileinfo_len)[0]
 9     fileinfo_str = (conn.recv(fileinfo_len)).decode(utf-8)
10     fileinfo_dic = json.loads(fileinfo_str)
11     file_path = os.path.join(base_path,usr,fileinfo_dic[filename])
12     with open(file_path,wb) as f:
13         while fileinfo_dic[filesize]:
14             content = conn.recv(1024)
15             fileinfo_dic[filesize] -= len(content)
16             f.write(content)
17     print(接收完毕)
operate_handler
技术分享图片
 1 import os
 2 import json
 3 import struct
 4 import socket
 5 
 6 def my_send(sk,operate_info):
 7     b_optinfo = (json.dumps(operate_info)).encode(utf-8)
 8     num = struct.pack(i, len(b_optinfo))
 9     sk.send(num)
10     sk.send(b_optinfo)
11 
12 # 上传
13 sk = socket.socket()
14 sk.connect((127.0.0.1,9000))
15 
16 # [登录,注册,退出]
17 
18 # [‘上传‘,‘下载‘,‘退出‘]
19 operate_info = {operate:upload,user:luke}
20 my_send(sk,operate_info)
21 # 我选择一个文件 发送到server端
22 file_path = rD:\6.udp协议.mp4
23 # 发送文件信息
24 file_name = os.path.basename(file_path)
25 file_size = os.path.getsize(file_path)
26 file_info = {filename:file_name,filesize:file_size}
27 my_send(sk,file_info)
28 # server端接收 写入
29 with open(file_path,rb) as f:
30     while file_size:
31         content = f.read(1024)
32         file_size -= len(content)
33         sk.send(content)
34 print(文件上传完毕)
client

 

上传下载

标签:hand   def   basename   发送   gif   info   luke   pen   upload   

原文地址:https://www.cnblogs.com/zhigu/p/9665069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!