I'm trying to build a simple echoing server with Websockets, but I can only get the connection to stay alive for a few seconds before I get an error. The reason I'm getting for the websocket closing is "Invalid UTF-8 bytes", but I'm not sure where those invalid bytes are coming from. Here is my websocket client:
// 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);
}
My server is Cherrypy with ws4py:
# 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))
When I run the app, this is what I get on the server side:
[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-
The last two messages also have an open rectangle after the second dash.
and this is what Chrome Dev Tools console says:
MessageEvent { data: "opening", type: "message" }
websocket closed: CloseEvent { code: 1007, reason: "Invalid UTF-8 bytes", type: "close" }
Where could these invalid bytes be coming from? It looks like all I'm doing is sending normal text. Thanks.
In your websocket-server.py
You have the line:
So it looks like the server thinks it is sending back a binary message but chrome is expecting text.
try: