我正在尝试编写一个 Python 程序,如果客户端连接到服务器,它可以浏览目录并使用套接字抓取文件。浏览部分工作正常,它打印出客户端的所有目录。 这是代码的一部分:
with clientsocket:
print('Connected to: ', addr)
while True:
m = input("Command > ")
clientsocket.send(m.encode('utf-8'))
data = clientsocket.recv(10000)
if m == "exit":
clientsocket.close()
if m.split()[0] == 'get':
inp = input("Filename > ")
while True:
rbuf = clientsocket.recv(8192)
if not rbuf:
break
d = open(inp, "ab")
d.write(rbuf)
d.close()
elif data.decode('utf-8').split()[0] == "LIST":
print(data.decode('utf-8'))
if not data:
break
然而,问题就出在这里:
if m.split()[0] == 'get':
inp = input("Filename > ")
while True:
rbuf = clientsocket.recv(8192)
if not rbuf:
break
好像陷入了死循环。更有趣的是,我试图接收的文件是 88.3kb,但文件在循环中返回的是 87kb,这非常接近......
我也试过一次接收一个 python 脚本(没有循环),它工作正常。
这是一些客户端代码:
while True:
msg = s.recv(1024).decode('utf-8')
if msg.split()[0] == "list":
dirs = os.listdir(msg.split()[1])
string = ''
for dira in dirs:
string += "LIST " + dira + "\n"
s.send(string.encode('utf-8'))
elif msg == "exit":
break
else:
#bit that sends the file
with open(msg.split()[1], 'rb') as r:
s.sendall(r.read())
所以我的问题是,如果我将它设置为在没有数据时关闭,为什么它会陷入无限循环,我该如何解决这个问题?
总的来说,我是网络编程的新手,所以如果我遗漏了一些明显的东西,请原谅我。
谢谢!
请您参考如下方法:
我想我知道问题出在哪里,但我可能错了。我多次遇到这样的情况,即使我指定了正确的长度,也没有在一次 recv 调用中收到整条消息。但是,您没有到达流的末尾,因此您的程序一直在等待剩余的 8192 个字节,但这些字节永远不会到达。
试试这个:
发送文件:
#bit that sends the file
with open(msg.split()[1], 'rb') as r:
data = r.read()
# check data length in bytes and send it to client
data_length = len(data)
s.send(data_length.to_bytes(4, 'big'))
s.send(data)
s.shutdown(socket.SHUT_RDWR)
s.close()
接收文件:
# check expected message length
remaining = int.from_bytes(clientsocket.recv(4), 'big')
d = open(inp, "wb")
while remaining:
# until there are bytes left...
# fetch remaining bytes or 4094 (whatever smaller)
rbuf = clientsocket.recv(min(remaining, 4096))
remaining -= len(rbuf)
# write to file
d.write(rbuf)
d.close()
