我是 python 新手,我正在尝试以下操作,我有两个 calsess:Server.py
and Client.py
我想将服务器目录中存在的所有文件发送到客户端的某个目录。 IE
C:\ServerDir\file1.txt
C:\ServerDir\file2.txt
C:\ServerDir\file3.txt...
会去:
D:\ClientDir\file1.txt
D:\ClientDir\file2.txt
D:\ClientDir\file3.txt...
现在我可以发送单个文件,服务器.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()
客户端.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
但它只发送第一个文件。
关键是 - 你怎么知道文件结束了?在您当前的实现中,如果连接结束,文件也会结束(然后您有一个关闭的套接字,因此没有机会处理下一个文件)。
有两种解决方案:
当然,您仍然存在服务器如何知道为传入文件分配什么文件名的问题。您可以将它们放入现在可能由文件名组成的“标头”中:)
如果您想知道,这正是(嗯,足够接近)HTTP 所做的事情。每个文件都有标题,然后是一个空行,然后是一个字节流,其长度之前由Content-Length
标头。之后,该连接可以重新用于下一个文件。如果Content-Length
丢失,代理将读取直到连接断开(并且下一个文件将需要建立新连接)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)