如何解决为什么我总是得到命令无法识别的输出
这是主机可以输入的命令
elif 'command' == "custom_dir":
conn.send(command.encode())
print("")
user_input = input(str("Custom Dir : "))
conn.send(user_input.encode())
print("")
print("Command has been sent")
print("")
files = conn.recv(5000)
files = files.decode()
print("Custom Dir Result : ",files)
else:
print("")
print("Command not recognized")
这是发送此命令的人(有时会崩溃)
elif 'command' == "custom_dir":
user_input = s.recv(5000)
user_input = user_input.decode()
files = os.listdir(user_input)
files = str(files)
s.send(files.encode())
print("")
print("Command has been executed successfully...")
print("")
else:
print("")
print("Command not recognized")
即使我将“命令”更改为命令,我仍然得到相同的输出
解决方法
'command'
是一个字符串文字。字符串 'command'
将永远等于字符串 "custom_dir"
。它与 5 == 6
相同 - 它们永远不会相等。
您的意思是要引用一个名为 command
的变量吗?在这种情况下,请写:
elif command == "custom_dir":
,
TCP 是一种不知道消息边界的流协议。您假设 conn.send(user_input.encode())
将完全完整地接收到 user_input = s.recv(5000)
,但事实并非如此。它可能只接收,比如“Docu”而不是“Documents”,或者更糟的是,只接收编码消息的一部分。有很多方法可以解决这个问题,而现有的许多协议(例如 XMLRPC、HTTP REST、zeromq 等)都提供了解决方案。
一种选择是使用 b"\n" 作为命令终止符(并且禁止在命令中使用 "\n")。使用 UTF-8,您可以扫描此终止符并分块接收。在发送端,只需使用 sendall(command.encode('utf-8' + b'\n')
并且接收端有一个例程,可以在使用前拆分 b'\n' 上的传入数据。这只是一种做事方式,但例子很好,所以...
类 RecvMsgUtf8:
def __init__(self,skt,recvsize=5000):
self.skt = skt
self.recvsize = recvsize
self.closed = False
self.commands = []
self.buf = []
def recvmsg(self):
while True:
# process pending commands
if self.commands:
command = self.commands.pop(0)
if not command:
self.closed = True
else:
return command.decode("utf-8")
if self.closed:
return ""
# get new commands
buf = self.skt.recv(self.recvsize)
if not buf:
self.commands.append(b"")
continue # back to command process
# split raw buffer into commands
self.buf += buf
while self.buf:
cmd_end = self.buf.find(b"\n")
if cmd_end == -1:
continue # process commands and wait for data
self.commands.append(self.buf[:cmd_end])
self.buf = self.buf[cmd_end:]
要使用它,您可以在接收器代码中执行更高的操作
receiver = RecvMsgUtf8(s,5000)
并在您当前的代码中,而不是 s.recv,做
receiver.recvmsg()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。