socket实现文件发送

ftp server

1.读取文件名

2.检测文件是否存在

3.打开文件

4.检测文件大小

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

6.等客户端确认

7.开始边读边发数据

8.发送md5

 

socket_server_ssh:

import  socket ,os
server = socket.socket()
server.bind(('localhost',9999))

server.listen()
while True:
    conn,addr = server.accept()
    print("new conn:",addr)
    while True:
        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()

        print("send done")
server.close()
View Code

 

socket_server_client:

import  socket
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:",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")
            f.close()
client.close()
View Code

 

posted @ 2017-11-04 12:15  _Cohen  阅读(230)  评论(0编辑  收藏  举报