Resolver el problema de congestión y ejercicios concurrentes.

Servidor

import socketserver 
import struct
import json

class MyRequestHandle (socketserver.BaseRequestHandler):
def handle (self):
print (self.client_address)
while True:
try:
cmd = self.request.recv (1024)

if len (cmd) == 0: descanso
de impresión (cmd.decode ( 'utf-8'))
con abierto (cmd, modo = 'rb') como f:
file = f.read ()

TOTAL_SIZE = len (archivo)

= header_dic {
"TOTAL_SIZE": TOTAL_SIZE,
"md5": "123123xi12ix12"
}

json_str = json.dumps (header_dic)
json_str_bytes = json_str.encode ('gbk')

x = struct.pack ('i', len (json_str_bytes))
self.request.send (x)

self.request.send (json_str_bytes)
self .request.send (file)

excepto Exception:
break
self.request.close ()

s = socketserver.ThreadingTCPServer (('127.0.0.1', 8080), MyRequestHandle)
s.serve_forever ()

Cliente

import struct 
import json
import os
from socket import *

client = socket (AF_INET, SOCK_STREAM)
client.connect (('127.0.0.1', 8080))

while True:
cmd = input ('请 输入 需要 下载 的 文件 地址 >> : ') .strip ()
si no es os.path.exists (cmd):
continuar
client.send (cmd.encode (' utf-8 '))
x = client.recv (4)
header_len = struct.unpack (' i ' , x) [0]
print (header_len)

json_str_bytes = client.recv (header_len)
json_str = json_str_bytes.decode ('utf-8')
header_dic = json.loads (json_str)
print (header_dic)
total_size = header_dic ["total_size"]

recv_size = 0
mientras recv_size <tamaño total:
recv_data = client.recv (1024)
recv_size + = len (recv_data)
file = recv_data
choice = cmd.rsplit ('.', 1) [1]
if choice == 'jpg':
with open (r'C: \ Users \ dell \ Desktop \ python14 \ day37 \ code \ download file \ copy.jpg ', mode =' ab ') como f:
f.write (file)
continue
elif choice ==' txt ':
con open (r'C: \ Users \ dell \ Desktop \ python14 \ day37 \ code \ download file \ job.txt ', mode =' ab ') como f:
f.write (file)
continue
elif choice ==' mp4 ':
con open (r 'C: \ Users \ dell \ Desktop \ python14 \ day37 \ code \ download file \ copy.mp4', mode = 'ab') como f:
f.escribir (archivo)
continuar
más:
print ()

Supongo que te gusta

Origin www.cnblogs.com/0B0S/p/12746765.html
Recomendado
Clasificación