首页 > 解决方案 > 在python中将文件从客户端上传到服务器,反之亦然

问题描述

开始用 C++ 实现这个项目,但是我认为 Python 将是未来 x 平台的更好选择。

这里的目标是创建一个简单的文件服务器,然后创建一个客户端。客户端应该能够将文件上传到服务器并从服务器下载文件。

我的客户代码是:

import socket

def Main():
        host = '127.0.0.1'
        port =  5000

        s = socket.socket()
        s.connect((host,port))

        choice = raw_input("Upload or Download? (u/d):")
        if choice == 'd':
            filename = raw_input("File to Download? (q to quit): ")
            if filename != 'q':
                s.send(filename)
                data = s.recv(1024)
                if data[:6] == "EXISTS":
                    filesize = long(data[6:])
                    message = raw_input("File found on the server!," +str(filesize)+"bytes, continue with download? y/n:")
                if message == "y":
                    s.send('OK')
                    f = open('new_'+filename, 'wb')
                    data = s.recv(1024)
                    totalRecv = len(data)
                    f.write(data)
                    while totalRecv < filesize:
                        data = s.recv(1024)
                        totalRecv += len(data)
                        f.write(data)
                        print ("Percentage Completed: "+"{0:.2f}".format((totalRecv/float(filesize))*100))
                    print ("File has been Downloaded!")
            else:
                print ("File doesnt exist!")
        else:
            filename = raw_input("File to Upload? (q to quit): ")
        #    if filename != 'q':

            print ("Upload Function Coming Soon")
        s.close()

if __name__ == '__main__':
    Main()

服务器的代码是:

import socket
import threading
import os

def RetrFile(name, sock):
    filename = sock.recv(1024)
    if os.path.isfile(filename):
        sock.send("EXISTS" + str(os.path.getsize(filename)))
        userResponse = sock.recv(1024)
        if userResponse[:2] == 'OK':
            with open(filename, 'rb') as f:
                bytesToSend = f.read(1024)
                sock.send(bytesToSend)
                while bytesToSend != "":
                    bytesToSend = f.read(1024)
                    sock.send(bytesToSend)
    else:
        sock.send("ERR")

    sock.close()

def Main():
    host = "127.0.0.1"
    port = 5000

    s = socket.socket()
    s.bind((host,port))

    s.listen(5)

    print ("Server Started")
    while True:
        c, addr = s.accept()
        print ("Client Connected:") + str(addr) + ">"
        t = threading.Thread(target=RetrFile, args=("retrThread", c))
        t.start()

    s.close()

if __name__ == '__main__':
    Main()

我已经很好地下载了文件,考虑一下,我应该能够对客户端的上传部分进行反向处理(而不是获取下载,我基本上复制服务器部分来执行上传) ...但是我似乎无法理解如何做到这一点。在这一点上,我并不担心硬编码端口等问题——稍后会解决这个问题,但是有人对此有任何建议吗?

我需要强调的是,我使用的是 python < v3(我知道它是旧的),但是它是我需要遵守的程序限制(因此 raw_input() v. input())

标签: python

解决方案


推荐阅读