Python学习-Socket实现简单的FTP服务端

78次阅读
没有评论

版本一

流程

ftp server

1. 读取文件名

2. 检测文件是否存在

3. 打开文件

4. 检测文件大小

5. 发送文件大小给客户端

6. 等客户端确认

7. 开始边读边发数据

8. 发送md5

服务端

# coding=utf-8
import socket
import os
import time
import hashlib
server = socket.socket()
server.bind(("localhost",6969))
server.listen(5)
print("Waiting for FTP conn....")

while True:
    conn,addr = server.accept()
    print("New conn:",addr)
    while True:
        print("Waiting new cmd...")
        data = conn.recv(1024)
        if not data:
            print("Client has lost..")
            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:    #逐行计算md5
                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()

客户端

# coding=utf-8

import socket
import hashlib
client = socket.socket()

client.connect(("localhost",6969))

while True:
    cmd = input(">>:").strip()
    if len(cmd) == 0: continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response = client.recv(1024)
        print("File size:",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")
        m = hashlib.md5()
       
        while received_size < file_total_size:
            if file_total_size - received_size > 1024: #如果总大小-收到的文件大小(即剩余的数据量)> 1024,则传输1024数据,负责,只传输剩余的数据(避免粘包)
                size = 1024
            else:
                size = file_total_size -received_size
            data = client.recv(size)
            received_size += len(data)
            f.write(data)
            m.update(data)
            #print(file_totle_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)
        print("client file md5:",new_file_md5)
client.close()

测试效果

1、执行server

Python学习-Socket实现简单的FTP服务端

2、执行client

Python学习-Socket实现简单的FTP服务端

3、执行get filename开始传输

Python学习-Socket实现简单的FTP服务端

Honest1y
版权声明:本站原创文章,由Honest1y于2018年07月16日发表,共计3540字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)