我想制作一个死掉的简单服务器,它可以接受来自客户端的不同类型的文件。问题是,我无法获得从客户端发送过来的文件名,因此无论调用什么文件,所有文件都保存为1个文件名。
这是我的客户。py:
import socket
with socket.socket() as s:
s.connect(('192.168.1.2',10000))
with open('Image.jpg','rb') as f:
s.sendall(f.read())
这是我的server.py:
import socket
print("Server started")
while True:
with socket.socket() as s:
s.bind(('192.168.1.2',10000))
s.listen(1)
with s.accept()[0] as c:
chunks = []
while True:
chunk = c.recv(4096)
if not chunk: break
chunks.append(chunk)
print("Receiving file")
with open('Image.jpg','wb') as f:
f.write(b''.join(chunks))
print("File Received")
哪个工作正常。问题开始了,如果我发送另一个文件,例如“ data.csv”,它将仍然在服务器上另存为“ Image.jpg”。
有什么办法可以将文件名和文件一起保存?
答案 0 :(得分:1)
我通常要做的是在数据之前发送文件名:
import socket
print("Server started")
while True:
with socket.socket() as s:
s.bind(('192.168.1.2',10000))
s.listen(1)
with s.accept()[0] as c:
chunks = []
while True:
filename = c.recv(1600)
filename = filename.decode()
chunk = c.recv(4096)
if not chunk: break
chunks.append(chunk)
print("Receiving file")
with open(filename,'wb') as f:
f.write(b''.join(chunks))
print("File Received")
客户:
import socket
import time
with socket.socket() as s:
s.connect(('192.168.1.2',10000))
with open('Image.jpg','rb') as f:
s.sendall('Image.jpg'.encode())
time.sleep(3)
s.sendall(f.read())