socket FTP-1

基于socket实现文件的传输以及md5验证

server:

 1 import socket
 2 import os
 3 import hashlib
 4 server=socket.socket()
 5 server.bind(('localhost',9090))
 6 server.listen()
 7 
 8 while True:
 9     print('ready to receive:')
10     conn,addr=server.accept()
11 
12     while True:
13         data1=conn.recv(1024)
14         file_name=data1.decode()
15 
16         if os.path.isfile(file_name):
17             file_size=os.path.getsize(file_name)
18             conn.send(str(file_size).encode())
19             f=open(file_name,'rb')
20             md=hashlib.md5()
21 
22             data2=conn.recv(1024)
23 
24             for line in f:
25                 conn.send(line)
26                 md.update(line)
27 
28 
29             f.close()
30             print('发送完成...')
31             conn.send(md.hexdigest().encode())
32 
33         else:
34             print('无文件')
35 
36 server.close()
 1 import socket
 2 import  os
 3 import hashlib
 4 
 5 
 6 client=socket.socket()
 7 client.connect(('localhost',9090))
 8 
 9 while True:
10     choice=input('>>')
11     if len(choice)==0:continue
12 
13     client.send(choice.encode())
14     data1=client.recv(1024)
15     data_size=int(data1.decode())
16     print('data_size:',data_size)
17 
18     count_size=0
19     recv_data=b''
20     # if os.path.isfile(choice):
21     f=open(choice+'.new','wb')
22     client.send(b'recving')
23     md=b''
24     ma_data=hashlib.md5(md)
25 
26     while count_size < data_size:
27         data=client.recv(1024)
28         recv_data+=data
29         recv_data_size=len(data.decode())
30         count_size+=recv_data_size
31         ma_data.update(data)
32 
33 
34     else:
35         f.write(recv_data)
36         print('complete')
37         f.close()
38 
39     md1=client.recv(1024).decode()
40     print(ma_data.hexdigest(),md1)
41     if ma_data.hexdigest()==md1:
42         print('无异常')
43 
44 client.close()

 

上一篇:DAY31、socket套接字


下一篇:十三.网络编程