1. 程式人生 > >socket_ftp

socket_ftp

server端
import socket,os,time,hashlib
server=socket.socket()
server.bind(('localhost',9999))
server.listen()

while True:
    conn,addr=server.accept()
    print("new connect:",addr)
    while True:
        print

("等待新指令")
        data=conn.recv(1024)
        if not data:
            print("客戶端已經斷開")
            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()) #send file size
            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
        print("send done")
server.close()

 

client端
import socket,hashlib
client=socket.socket()
client.connect(('localhost',9999))

while True:
    cmd=input("請輸入:").strip()
    if len(cmd)==0:continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response=client.recv(1024)
        print("檔案大小:",server_response.decode())
        client.send(b"ready to rece file")
        file_total_size=int(server_response.decode())
        received_size=0
        filename=cmd.split()[1]
        f=open(filename +".new","wb")
        m=hashlib.md5()
        while received_size < file_total_size:
            if file_total_size - received_size >1024: #要收不止一次
                size=1024
            else: #最後一次了,剩多少收多少
                size=file_total_size - received_size
                print("last recevive:",size)
            data=client.recv(1024)
            received_size+=len(data)
            m.update(data)
            f.write(data)
            #print(file_total_size,received_size)
        else:
            new_file_md5=m.hexdigest()
            print("file recv done",received_size,file_total_size)
            f.close()
        server_file_md5=client.recv(1024)
        print("server file md5:",server_file_md5.decode())
        print("client file md5:",new_file_md5)
client.close()