【问题标题】:Why I get Type Error: descriptor 'encode' for 'str' objects doesn't apply to a 'bytes' object为什么我得到类型错误:“str”对象的描述符“encode”不适用于“bytes”对象
【发布时间】:2022-07-22 16:23:02
【问题描述】:

服务器代码:https://github.com/Ohyo17/project/blob/master/server.py

客户端代码:https://github.com/Ohyo17/project/blob/master/client.py

for fd in outputfd:
        try:
            if roomCount > 0:
                message = messageQueue[fd].get_nowait()
                fd.send(str.encode(message)) #error in here
        except queue.Empty:
            output.remove(fd)

【问题讨论】:

    标签: python sockets


    【解决方案1】:

    您正在尝试将字符串转换为字节表示,但您的 message 很可能已经是字节形式,这就是您收到该错误的原因。

    如果是这样,您可以直接将其传递给fd.send()

    Python documentation 声明:

    [...] 可以使用字节的 decode() 方法创建一个字符串。

    bytes.decode() 的相反方法是 str.encode(),它返回一个 Unicode 字符串的字节表示,在请求中编码 编码。

    str.encode() 仅在您输入字节时有效,bytes.decode() 仅在您输入字符串时有效。

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 2021-10-26
      • 2021-05-31
      • 2020-08-12
      • 2021-09-14
      • 2022-01-21
      • 2020-11-01
      • 1970-01-01
      相关资源
      最近更新 更多