【发布时间】:2010-12-14 15:01:47
【问题描述】:
我正在做一些套接字/选择编程,我的一个事件是由'OK' 的传入字节字符串触发的。我正在使用 utf_8 对从服务器发送的所有内容进行编码并在客户端对其进行解码。但是,我的客户比较不起作用,我的 if 语句永远不会评估为真。这是有问题的代码:
服务器端:
def broadcast_string(self, data, omit_sock): # broadcasts data utf_8 encoded to all socks
for sock in self.descriptors:
if sock is not self.server and sock is not omit_sock:
sock.send(data.encode('utf_8'))
print(data)
def start_game(self): # i call this to send 'OK'
data = 'OK'
self.broadcast_string(data, 0)
self.new_round()
客户端:
else: # got data from server
if data.decode('utf_8') == 'OK': # i've tried substituting this with a var, no luck
self.playstarted = True
else:
sys.stdout.write(data.decode('utf_8') + "\n")
sys.stdout.flush()
if self.playstarted is True: # never reached because if statement never True
command = input("-->")
我读过this,我想我正在关注它,但显然没有。我什至使用 python shell 完成了示例,并让它们评估为True,但在我运行这个程序时没有。
谢谢!
【问题讨论】:
-
您应该点击“其他”。打印什么?
-
OK 被打印到标准输出。抱歉,我编辑了缩进以使其更清晰。最后一个 if 语句不应该嵌套在 if,else 中。
-
在python3中,
str还是类型名吗?因为你可能只是在调用 type 方法。 -
我的字符串存储在str中,我知道模棱两可。我会尝试更改它,看看是否有帮助。
-
当您将以
sys.stdout.write....开头的两行替换为仅print(data)时,输出会发生什么情况?
标签: python sockets select encoding