python(Liunx上的fpt传送文件md5)

Client

# Author:Sooele
import socket
client = socket.socket()

#client.connect(('192.168.16.200',9999))
client.connect(('localhost',9999))

while True:
    cmd = input(">>:").strip()
    if len(cmd) == 0: continue
    if cmd.startswith("get"): #startswith #开始的位置
       client.send(cmd.encode())#encode转化为需要的格式
       server_response = client.recv(1024)
       print("servr response:",server_response)
       client.send(b"ready to recv file")
       file_total_size = int(server_response.decode())#文件全部大小 = 客户端返回的文件大小
       received_size = 0
       filename = cmd.split()[1] #文件的名字
       f = open(filename + ".new","wb")
       while received_size < file_total_size:
         data = client.recv(1024)
         received_size += len(data)
         f.write(data)
         #print(file_total_size,received_size)
       else:
         print("file recv done", received_size,file_total_size)
         f.close()


client.close()

server

# Author:Sooele
import hashlib
import socket ,os,time
server = socket.socket()
server.bind(('0.0.0.0',9999) )
server.listen()
while True:
    conn, addr = server.accept()
    print("new conn:",addr)
    while True:
        print("等待新指令")
        data = conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
        cmd,filename = data.decode().split()   ##字符串要decode   #filename文件名字
        print(filename)
        if os.path.isfile(filename): #判断filename是否是一个文件
           f = open(filename,"rb")#如是filename是文件,就打开
           m = hashlib.md5()
           file_size = os.stat(filename).st_size#文件大小,等于os模块统计filename文件的大小
           conn.send( str(file_size).encode() )#发送文件大小 #str将对象 x 转换为字符串
           conn.recv(1024)#wait for ack #等一下
           for line in f:
              m.update(line)
              conn.send(line)
           print("file md5", m.hexdigest())
           f.close()
           conn.send(m.hexdigest().encode()) #send md5 #hexdigest 16进制
        print("send done")

server.close()

发表评论