I am trying to create a 2-way communication between server and client using Flask
and socket.io
.
Everything works fine until server receives utf-8
string from client, which gets garbled. Sending from server to client works fine, and prior to sending from client to server, the client prints the message correctly.
Here is some code that reproduces the problem:
app.py:
import flask
from flask_socketio import SocketIO, emit, disconnect
import json
app = flask.Flask(__name__)
socket_io = SocketIO(app)
@socket_io.on('pull')
def socket_io_handle_pull():
json_msg = {
'msg': "abcćčddžđefghijklmnnjoprsštuvzž"
}
print("Pushing", json_msg)
socket_io.emit('response', json_msg)
@socket_io.on('push')
def socket_io_handle_push(json_msg):
print("Pushed:", json_msg)
@socket_io.on('disconnect')
def socket_io_handle_disconnect():
disconnect()
@app.route('/')
def root():
return flask.render_template(
'index.html'
)
if __name__ == '__main__':
socket_io.run(app)
index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('response', json => {
socket.emit('push', json);
})
socket.emit('pull');
</script>
</body>
</html>
Output:
Pushing {'msg': 'abcćčddžđefghijklmnnjoprsštuvzž'}
Pushed: {'msg': 'abcÄ\x87Ä\x8dddA3Ä\x91efghijklmnnjoprsA!tuvzA3'}