我正在尝试使用 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 开发工具控制台所说的:
MessageEvent { data: "opening", type: "message" }
websocket closed: CloseEvent { code: 1007, reason: "Invalid UTF-8 bytes", type: "close" }
这些无效字节可能来自哪里?看起来我所做的只是发送普通文本。谢谢。