从客户端接收“utf-8"的问题

人气:985 发布:2022-10-16 标签: python flask socket.io flask-socketio

问题描述

我正在尝试使用 Flasksocket.io 在服务器和客户端之间创建 2 路通信.

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.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>

输出:

Pushing {'msg': 'abcćčddžđefghijklmnnjoprsštuvzž'}
Pushed: {'msg': 'abcÄx87Äx8dddA3Äx91efghijklmnnjoprsA!tuvzA3'}

推荐答案

您使用的是 Socket.IO 客户端的 1.x 版本,它具有 已知问题 UTF-8 字符串的双重编码.您应该尝试解决此问题的 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.

238