python--"Client and server file download

Source: Internet
Author: User


Before we introduce, we need to understand a cryptographic algorithm

The MD5 checksum (checksum) checks the correctness of the data by performing a hash operation on the received transmitted data. The computed hash value is compared with the hash value of the data transfer. If the two values are the same, the transmitted data is intact and not altered (provided the hash value has not been tampered with) so that it can be used with confidence.

If the customer to our data center synchronization of a file, the file using MD5 checksum, then the customer sends a file at the same time will send a verification code of the file, we get the file to do MD5 operation, the results of the calculation and the customer to send a comparison of the checksum, if the agreement that the customer sent a file without error, Otherwise, a file error is considered to be sent again.

Also noteworthy is that the file transfer process, there are some sticky packet problems, this issue, I will be listed separately blog to organize

Please expect

Also due to personal time limit, upload files temporarily moved to tomorrow (note that the file here refers to the format of Txt,jpg,png, not the folder, about the folder, we will put it on a Web download, here do not do processing)

The first thing to do: build first

Server = Socket.socket ()

Server.bind ((' localhost ', 6666))

Server.listen ()

While True:

conn, addr = Server.accept ()

Print ("New addr:", addr)

This is a fairly formatted section that establishes the server, connects with the client, and prints the client's address

Client = Socket.socket ()

Client.connect ((' localhost ', 6666))

In the same vein, this is the client

While True:

cmd = input (">>>:"). Strip ()

If Len (cmd) ==0:

Continue

If Cmd.startswith ("Get"):

filename = Cmd.split () [1] #获取文件名

Client.send (Cmd.encode ("Utf-8")) #客户端把要下载的文件信息, hand over to the server

This last section has been shared, not explained here.

This is what the client asks you to enter the file source, the input format is

Get C:\Users\Public\Pictures\938876-20160611152927293-1786781422.png

There is a classmate, there will be doubts Cmd.split () [1], why is it a wow, can not be two or three?

C:\Users\Public\Pictures\938876-20160611152927293-1786781422.png

Note that there is a space in front of him, so that one of the following can be extracted

While True:

data = CONN.RECV (1024)

If not data:

Print ("Client disconnected ... ")

Break

CMD, filename = Data.decode (). Split () #对信息进行解码, and remove a space to convert to two strings

Print (filename)

Server to accept, where filename is the source of your file

If Os.path.isfile (filename):

This step is to determine if the file exists, and if it exists, you can proceed

f = open (filename, "RB") #打开文件

File_size = Os.stat (filename). st_size

Conn.send (str (file_size). Encode ("Utf-8")) #发送文件大小

Send File Size

The client begins to accept the file size:

Server_resp_size = Client.recv (1024x768) #接收文件总的大小

file_total_size = Int (Server_resp_size.decode ())

Print ("File size:", server_resp_size) #将文件大小进行打印

You can learn here, but you still have questions? If you have any questions, please contact us.

The first stage above, has been completed, the next is the official file download phase

Client.send (b "Ready to recv File ...") #客户端, send a message, I'm going to start receiving files.

CONN.RECV (1024x768) #服务端, receiving messages

Service end for line in F:

M.update (line)

Conn.send (line)

Start traversing files, updating messages

Client, F = open (filename+ ". New", "WB"), create a file in new format to receive the service

Messages sent from the end

The client begins to accept the file

While Recv_size < file_total_size: #目的是为了防止黏包问题出现

If File_total_size-recv_size > 1024x768: #判断最后一次, before receive size set to 1024

Size = 1024

else: #最后一次不足1024, only the remainder of the file is received and does not contain MD5

Size = File_total_size-recv_size

Print ("The Last Size:", size)

data = CLIENT.RECV (size)

Recv_size + = len (data)

F.write (data)


Service-side general idea:


650) this.width=650; "Src=" Https://s1.51cto.com/oss/201711/15/09f753100746e0a921c363a050d26e62.png-wh_500x0-wm_3 -wmp_4-s_3391020654.png "title=" Wen.png "alt=" 09f753100746e0a921c363a050d26e62.png-wh_ "/>










So the total service-side code

Import Os,socket,hashlib

Server = Socket.socket ()
Server.bind ((' localhost ', 9999))
Server.listen ()

While True:
conn, addr = Server.accept ()
Print ("New addr:", addr)
While True:
data = CONN.RECV (1024)
If not data:
Print ("Client disconnected ... ")
Break
CMD, filename = Data.decode (). Split ()
Print (filename)
If Os.path.isfile (filename):
f = open (filename, "RB")
m = Hashlib.md5 ()
File_size = Os.stat (filename). st_size
Conn.send (str (file_size). Encode ("Utf-8")) #发送文件大小
CONN.RECV (1024x768) #等待回复
For line in F:
M.update (line)
Conn.send (line)
Print ("File md5:", M.hexdigest ())
F.close ()
Conn.send (M.hexdigest (). Encode ("Utf-8")) #发送MD5, sticky packets may appear with the above "Conn.send (line)"
Print ("Send done ...")

Server.close ()






650) this.width=650; "Src=" Https://s5.51cto.com/oss/201711/15/69536ea6ea36d8d8d2b18756fdbd86f0.png-wh_500x0-wm_3 -wmp_4-s_1452155190.png "title=" qq picture 20171115210724.png "alt=" 69536ea6ea36d8d8d2b18756fdbd86f0.png-wh_ "/>


Client code:

Import Socket,hashlib

Client = Socket.socket ()
Client.connect ((' localhost ', 9999))

While True:
cmd = input ("&GT;&GT;&GT;:"). Strip ()
If Len (cmd) ==0:
Continue
If Cmd.startswith ("Get"):
filename = Cmd.split () [1] #获取文件名
Client.send (Cmd.encode ("Utf-8"))
Server_resp_size = Client.recv (1024x768) #接收文件总的大小
file_total_size = Int (Server_resp_size.decode ())
Print ("File size:", server_resp_size)
Client.send (b "Ready to recv File ...")
f = open (filename+ ". New", "WB")
Recv_size = 0
m = Hashlib.md5 ()
While Recv_size < file_total_size:
If File_total_size-recv_size > 1024x768: #判断最后一次, before receive size set to 1024
Size = 1024
else: #最后一次不足1024, only the remainder of the file is received and does not contain MD5
Size = File_total_size-recv_size
Print ("The Last Size:", size)
data = CLIENT.RECV (size)
Recv_size + = len (data)
F.write (data)
M.update (data)
Else
CLIENT_MD5 = M.hexdigest ()
Print ("recv done ...")
Print ("Total size:", File_total_size, "had been received:", recv_size)
SERVER_MD5 = CLIENT.RECV (1024)
Print ("Server MD5:", CLIENT_MD5, "Server MD5:", Server_md5.decode ())
F.close ()

Client.close ()

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/15/5507e250234ea7fb1723ef7bb92496f0.png-wh_500x0-wm_3 -wmp_4-s_3346951819.png "style=" Float:none; "title=" QQ picture 20171115211600.png "alt=" 5507e250234ea7fb1723ef7bb92496f0.png-wh_ "/>

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/15/af0b77968ab298adf36621e83122f800.png-wh_500x0-wm_3 -wmp_4-s_3827459950.png "style=" Float:none; "title=" QQ picture 20171115211543.png "alt=" Af0b77968ab298adf36621e83122f800.png-wh_ "/>

650) this.width=650; "Src=" Https://s4.51cto.com/oss/201711/15/8c27a4f62e0f537e6a2444f7fc8992d1.png-wh_500x0-wm_3 -wmp_4-s_2928388090.png "style=" Float:none; "title=" QQ picture 20171115211608.png "alt=" 8c27a4f62e0f537e6a2444f7fc8992d1.png-wh_ "/>


python--"Client and server file download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.