【问题标题】:comparing strings and decoded unicode in python3比较python3中的字符串和解码的unicode
【发布时间】: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


【解决方案1】:

TCP 套接字没有消息边界。正如您的最后一条评论所说,您在一个长字符串中收到多条消息。您有责任对数据进行排队,直到获得一条完整的消息,然后将其作为一条完整的消息进行处理。

每次select 说套接字有一些数据要读取,将数据附加到 read 缓冲区,然后检查缓冲区是否包含完整的消息。如果是,则仅从缓冲区的前面提取消息并进行处理。继续直到找不到更多完整的消息,然后再次调用select。另请注意,您应该只decode 一条完整的消息,否则您可能会收到部分 UTF-8 多字节字符。

使用\n 作为消息终止符的粗略示例(无错误处理):

tmp = sock.recv(1000)
readbuf += tmp
while b'\n' in readbuf:
    msg,readbuf = readbuf.split(b'\n',1)
    process(msg.decode('utf8'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2021-09-24
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多