【问题标题】:sending multiple files in python在python中发送多个文件
【发布时间】:2018-10-24 19:27:41
【问题描述】:

我是 python 新手,我正在尝试以下方法,我有两个 calsess:Server.pyClient.py 我想将服务器目录中存在的所有文件发送到客户端的某个目录。即

C:\ServerDir\file1.txt

C:\ServerDir\file2.txt

C:\ServerDir\file3.txt...

会去:

D:\ClientDir\file1.txt

D:\ClientDir\file2.txt

D:\ClientDir\file3.txt...

现在我可以发送单个文件,Server.py

   import socket                   # Import socket module

port = 60000                    # Reserve a port for your service.
s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
s.bind((host, port))            # Bind to the port
s.listen(5)                     # Now wait for client connection.

print ('Server listening....')

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print ('Got connection from', addr)
    data = conn.recv(1024)
    print('Server received', repr(data))

    filename='C:\\Users\\Desktop\\File.txt'
    f = open(filename,'rb')
    l = f.read(1024)
    while (l):
       conn.send(l)
       print('Sent ',repr(l))
       l = f.read(1024)
    f.close()

    print('Done sending')
    conn.send('Thank you for connecting'.encode())
    conn.close()

Client.py:

    import socket                   # Import socket module

s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
port = 60000                    # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!".encode())

with open('C:\\Users\\Desktop\\Python\\gg.txt', 'wb') as f:
    print ('file opened')
    while True:
        print('receiving data...')
        data = s.recv(1024)
        print('data=%s', (data))
        if not data:
            break
        # write data to a file
        f.write(data)

f.close()
print('Successfully get the file')
s.close()
print('connection closed')

我尝试遍历服务器端的所有文件,例如:

 for file in os.listdir('C:\\Users\\Desktop\\'):
    filename = 'C:\\Users\\Desktop\\'+file 

但它只发送第一个文件。

【问题讨论】:

    标签: python


    【解决方案1】:

    关键是 - 你怎么知道文件结束了?在你当前的实现中,如果连接结束,文件也会结束(然后你有一个关闭的套接字,所以没有机会获得下一个文件)。

    有两种解决方案:

    • 简单:让客户端为每个文件打开一个新连接(即将内容移动到循环中);如果你的连接瞬间中断,也许一切都结束了

    • 更好:让服务器在文件本身之前发送文件大小。让客户端只将数据写入文件直到大小正确,然后开始处理新文件。

    当然,您仍然对服务器如何知道分配传入文件的文件名有疑问。您可以将它们放入现在可能包含文件名的“标题”中:)

    如果您想知道,这正是(嗯,足够接近)HTTP 所做的事情。每个文件都有标题,然后是一个空行,然后是一个字节流,其长度之前由Content-Length 标题传达。之后,可以将连接重新用于下一个文件。如果Content-Length 丢失,代理将读取直到连接断开(下一个文件需要建立新连接)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2020-06-20
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多