使用socketserver实现简单的下载和上传
1.文件下载功能,服务端和客户端分别在不同文件夹,客户端可以上传客户端当前文件夹的文件,可以下载服务器端文件夹的文件.需要知道文件的全名.
#服务端
import socketserver
import struct
import json
import os
class MyTCP(socketserver.BaseRequestHandler):
def handle(self):
try:
while True:
adress = self.client_address
b_dic_len = self.request.recv(4)
dic_len = struct.unpack('i',b_dic_len)[0]
dic = json.loads(self.request.recv(dic_len))
if dic['func'] == '1':
print(adress,dic,dic['size'])
l = dic['size']
count = 0
data = b''
with open(dic['name'], 'wb') as f:
while count < l:
if l < 1024:
data_temp = self.request.recv(l)
else:
if l - count >= 1024:
data_temp = self.request.recv(1024)
print(data_temp)
else:
data_temp = self.request.recv(l - count)
data += data_temp
count += len(data_temp)
f.write(data)
if dic['func'] == '2':
if os.path.exists(dic['name']):
dic1 = {'name':dic['name'],'size': os.path.getsize(dic['name'])}
dic_b = bytes(json.dumps(dic1), 'utf-8')
dic_b_len = len(dic_b)
obj = struct.pack('i', dic_b_len)
self.request.send(obj)
self.request.send(dic_b)
with open(dic['name'], 'rb') as f:
for line in f:
print(line)
self.request.send(line)
except Exception:
pass
ss = socketserver.ThreadingTCPServer(('127.0.0.1',8002),MyTCP)
ss.serve_forever()
#客户端
import socket
import json
import struct
import os
soc = socket.socket()
soc.connect(('127.0.0.1',8002))
while True:
print("""
1.上传
2.下载
""")
func = input('请输入你要选择的功能编号:')
if func not in ['1','2']:
print('你的输入有误')
filename = input('请输入文件名:')
if func == '1':
dic1 = {'func':func,'name':filename,'size':os.path.getsize(filename)}
dic_b = bytes(json.dumps(dic1), 'utf-8')
dic_b_len = len(dic_b)
obj = struct.pack('i', dic_b_len)
soc.send(obj)
soc.send(dic_b)
with open(filename, 'rb') as f:
for line in f:
print(line)
soc.send(line)
elif func == '2':
dic1 = {'func': func, 'name': filename}
dic_b = bytes(json.dumps(dic1), 'utf-8')
dic_b_len = len(dic_b)
obj = struct.pack('i', dic_b_len)
soc.send(obj)
soc.send(dic_b)
b_dic_len = soc.recv(4)
dic_len = struct.unpack('i', b_dic_len)[0]
dic = json.loads(soc.recv(dic_len))
l = dic['size']
count = 0
data = b''
with open(dic['name'], 'wb') as f:
while count < l:
if l < 1024:
data_temp = soc.recv(l)
else:
if l - count >= 1024:
data_temp = soc.recv(1024)
print(data_temp)
else:
data_temp = soc.recv(l - count)
data += data_temp
count += len(data_temp)
f.write(data)
#服务端
import socket
soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
soc.bind(('127.0.0.1',8001))
while True:
data,addr = soc.recvfrom(1024)
print(data)
soc.sendto(data.upper(),addr)
#客户端
import socket
soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
soc.sendto('gcgcgcgc'.encode('utf8'),('127.0.0.1',8001))
data,addr = soc.recvfrom(1024)
print(data)