【问题标题】:read TextMessage ws4py on python 3在 python 3 上阅读 TextMessage ws4py
【发布时间】:2013-10-05 08:41:45
【问题描述】:

我使用 ws4py 0.3.2 创建了一个 Web 服务器套接字,它在 python 3.3.2 上使用了 cherrypy 3.2.4。当我尝试打印客户端发送到服务器的消息时,例如 this

class ChatWebSocketHandler(WebSocket):
    def received_message(self, m):
        cherrypy.log("[+] Message => {%d} %s" % (len(m), m))
        cherrypy.engine.publish('websocket-broadcast', m)

我收到错误消息:

  File "./server.py", line 13, in received_message
    cherrypy.log("[+] Message => {%d} %s" % (len(m), m))
TypeError: __str__ returned non-string (type bytes)

【问题讨论】:

  • 将cherrypy.log("[+] Message => {%d} %s" % (len(m), m)) 替换为cherrypy.log("[+] Message => {%d} %r" % (len(m), m))。然后会发生什么?
  • 输出关闭cherrypy.log("[+] Message => {%d} %r" % (len(m), m)) 是:[+] Message => {46} <ws4py.messaging.TextMessage object at 0x7f15d8785650>

标签: python-3.x cherrypy ws4py


【解决方案1】:

返回的对象是TextMessage或BinaryMessage类型,所以不能直接转换成字符串。要获取有效负载(在本例中为字符串),您需要访问 data 属性:

像这样:

def received_message(self, m):
  if m.is_text:
    recvStr = m.data.decode("utf-8")
    print(recvStr)

希望这个有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多