Python客户机/服务器发送大文件

2024-10-01 13:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定是否有人回答了这个问题,如果我很抱歉:

我有一个简单的python脚本,它将所有文件发送到一个文件夹中:

客户:

import os,sys, socket, time
def Send(sok,data,end="292929"):
    sok.sendall(data + end);
def SendFolder(sok,folder):
    if(os.path.isdir(folder)):
        files = os.listdir(folder);
        os.chdir(folder);
        for file_ in files:
            Send(sok,file_);#Send the file name to the server
            f = open(file_, "rb");
            while(True):
                d = f.read();#read file
                if(d == ""):
                    break;
                Send(sok, d, "");#Send file data
            f.close();
            time.sleep(0.8);#Problem here!!!!!!!!!!!
            Send(sok,"");#Send termination to the server
            time.sleep(1);#Wait the server to write the file
        os.chdir("..");
        Send(sok,"endfile");#let the server know that we finish sending files
    else:
        Send("endfile")#If not folder send termination
try:
    sok1 = socket.socket();
    sok1.connect(("192.168.1.121",4444))#local ip
    time.sleep(1);
    while(True):
        Send(sok1,"Enter folder name to download: ");
        r = sok1.recv(1024);
        SendFolder(sok1,r);
        time.sleep(0.5);
except BaseException, e:
    print "Error: " + str(e);
    os._exit(1);

服务器:

^{pr2}$

我知道这不是最好的服务器…但我知道。我等待的是一个小的文件夹,因为它没有足够的时间来处理大的文件。在

所以我的问题是如何将文件发送到服务器而不需要客户端等待??或者确切知道客户端需要等待服务器接收文件的时间??一些代码也一样,但是可以处理任意大小的文件,有什么帮助吗?在


Tags: 文件theto服务器senddataservertime
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:38

TCP sockets are byte streams, not message streams。如果你想发送一系列独立的消息(比如你的独立文件),你需要定义一个协议,然后写一个协议处理程序。这是没有办法的;仅仅猜测时间或试图利用包边界是不可能的。在

上面链接的博客文章展示了一种方法。但如果需要,可以使用字符串分隔符。但你必须处理两个问题:

  • 分隔符可以出现在read包中的任何位置,而不仅仅是在末尾。在
  • 分隔符可以在数据包边界上拆分,您可以在一次读取结束时得到"2929",在下一次读取开始时得到另一个{}。在

通常的方法是积累一个缓冲区,然后在缓冲区中的任何地方搜索分隔符。像这样:

def message(sock, delimiter):
    buf = ''
    while True:
        data = sock.read(4096)
        if not data:
            # If the socket closes with no delimiter, this will
            # treat the last "partial file" as a complete file.
            # If that's not what you want, just return, or raise.
            yield buf
            return
        buf += data
        messages = buf.split(delimiter)
        for message in messages[:-1]:
            yield message
        buf = message[-1]

同时,您的定界符还有另一个问题:没有什么可以阻止它出现在您试图传输的文件中。例如,如果你试图发送你的脚本,或者这个网页呢?在

这也是其他协议通常优于分隔符的原因之一,但这并不难处理:只需转义文件中找到的任何分隔符。因为您一次发送整个文件,所以您只需在sendall之前使用replace,在{}之前使用replace。在

相关问题 更多 >