read TextMessage ws4py on python 3

1.3k Views Asked by At

I have created a web server socket using ws4py 0.3.2 and which uses cherrypy 3.2.4 on python 3.3.2 .When I try to print Message of client send to server like this

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

I got error message :

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

There are 1 best solutions below

0
On

The returned object is of type TextMessage or BinaryMessage, so you can't cast it to a string directly. To get to the payload (string, in this case) you need to access the data attribute:

Like this:

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

Hope this is usable.