我正在尝试使用 Flask 和 socket.io 在服务器和客户端之间建立双向通信.
I am trying to create a 2-way communication between server and client using Flask and socket.io.
一切正常,直到服务器从客户端收到 utf-8 字符串,该字符串会出现乱码.从服务器发送到客户端的工作正常,并且在从客户端发送到服务器之前,客户端可以正确打印消息.
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:
index.html:
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="//cdnjs.cloudflare/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script> </head> <body> <script type="text/javascript"> var socket = io.connect('' + document.domain + ':' + location.port); socket.on('response', json => { socket.emit('push', json); }) socket.emit('pull'); </script> </body> </html>输出:
Pushing {'msg': 'abcćčddžđefghijklmnnjoprsštuvzž'} Pushed: {'msg': 'abcÄ\x87Ä\x8dddA3Ä\x91efghijklmnnjoprsA!tuvzA3'} 推荐答案您正在使用Socket.IO客户端的1.x版本,该客户端具有已知问题.您应该尝试解决此问题的2.x版本.
You are using the 1.x versions of the Socket.IO client, which had known problems with double-encoding of UTF-8 strings. You should try the 2.x versions which have resolved this issue.
更多推荐
从客户端接收"utf
发布评论