【问题标题】:i am creating a multi-client chat application in python using socket我正在使用套接字在 python 中创建一个多客户端聊天应用程序
【发布时间】:2018-08-20 13:57:06
【问题描述】:

在服务器端对字符串进行编码时出错。它抛出以下错误:

broadcast(bytes(msg, "utf8")) TypeError: encoding without a string 论据

这是我的代码

msg = "%s from  has joined the chat!",name
broadcast(bytes(msg, "utf8"))

虽然我使用字符串参数对其进行编码。 有什么我想念的吗?

【问题讨论】:

    标签: python sockets serversocket


    【解决方案1】:

    如果name是一个字符串,你写msg = "%s from has joined the chat!",name,你会收到一个字符串元组,第一个元素是“%s from has加入聊天!”,第二个-名字字符串的值。

    加入字符串试试:

     msg = "%s from  has joined the chat!" + name
    

    或者在这种情况下可能:

    msg = name + "has joined the chat!"
    

    【讨论】:

    • 或者使用python 3.6 f-string,就像msg = f'{name} has joind the chat!'
    【解决方案2】:

    bytes() 不适用于使用 % 格式制作的字符串,您可以使用以下格式进行格式化:

    msg = "{} from has joined the chat!".format(name)
    

    或来自 python 3.6:

    msg = f"{name} from has joined the chat!"
    

    这是因为在您的代码中 msg 实际上是一个元组(尝试查看 type(msg)),像 print() 这样的函数可以将该元组转换为字符串,但 bytes() 不会这样做

    【讨论】:

      【解决方案3】:

      你可以替换这个

      msg = "%s from  has joined the chat!",name
      

      有了这个

      msg = "%s from  has joined the chat!" % name
      

      还有这个

      broadcast(bytes(msg, "utf8"))
      

      有了这个

      broadcast(msg.encode("utf8"))
      

      就是这样

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-10
        • 2018-01-06
        • 2016-07-03
        • 2020-10-10
        • 1970-01-01
        • 2020-03-21
        • 1970-01-01
        相关资源
        最近更新 更多