Websockets - 无效的UTF-8字节

时间:2016-02-08 04:48:08

标签: python utf-8 websocket ws4py

我正在尝试使用Websockets构建一个简单的回显服务器,但我只能让连接在我收到错误之前保持活动几秒钟。我得到的websocket关闭的原因是"无效的UTF-8字节",但我不确定那些无效字节来自哪里。这是我的websocket客户端:

// websocket-client.es6
this.ws = new WebSocket(`ws://localhost:8080/websocket-test/ws`);
this.ws.onopen = (event) => {
  this.ws.send('opening');
  setInterval(() => {
    this.ws.send('heartbeat');
  }, 5000);
};
this.ws.onmessage = (event) => {
  console.log(event);
};
this.ws.onclose = (event) => {
  console.log('websocket closing: %O', event);
};
this.ws.onerror = (event) => {
  console.error('error: %O', event);
}

我的服务器是带有ws4py的Cherrypy:

# websocket-server.py
class MyWebSocket(WebSocket):
    def received_message(self, message):
        cherrypy.log('received %s' % message)
        self.send(message.data, message.is_binary)

    def closed(self, code, reason=None):
        cherrypy.log('closed. code %s, reason: %s' % (code, reason))

当我运行应用程序时,这就是我在服务器端获得的内容:

[10/Feb/2016:16:39:42]  received opening
[10/Feb/2016:16:39:47]  received --heartbeat--
[10/Feb/2016:16:39:52]  received --heartbeat--
[10/Feb/2016:16:39:57]  received --heartbeat--
[10/Feb/2016:16:40:02]  received --heartbeat--
[10/Feb/2016:16:40:07]  received --heartbeat--
[10/Feb/2016:16:40:12]  received --heartbeat--
[10/Feb/2016:16:40:17]  received -heLrtbHat-5
[10/Feb/2016:16:40:22]  received -heLrtbHat-

在第二个破折号后,最后两条消息也有一个打开的矩形。

这就是Chrome Dev Tools控制台所说的:

MessageEvent { data: "opening", type: "message" }
websocket closed: CloseEvent { code: 1007, reason: "Invalid UTF-8 bytes", type: "close" }

这些无效字节可能来自哪里?看起来我正在做的就是发送普通文本。感谢。

1 个答案:

答案 0 :(得分:0)

在你的websocket-server.py

你有这条线:

self.send(message.data, message.is_binary)

所以看起来服务器认为它正在发回二进制消息,但chrome期待文本。

尝试:

self.send(message.data, message.is_text)