简体   繁体   English

websocket发送汉字

[英]websocket send Chinese characters

I have a websocket server write by python and a websocket client write by javaScript. 我有一个由python编写的websocket服务器和一个由javaScript编写的websocket客户端。

when use English characters like 'hahaha', they can send messages to each other and work well. 当使用英文字符(例如“ haha​​ha”)时,它们可以相互发送消息并运行良好。

when use Chinese characters like '哈哈', the server can recieve the message and I decode the message in python side then work well. 当使用“哈哈”等汉字时,服务器可以接收到该消息,并且我在python端对该消息进行解码,然后可以正常工作。 But when the server send the '哈哈' characters to the client, it said that WebSocket connection to 'ws://localhost:3369/' failed: Could not decode a text frame as UTF-8. 但是,当服务器将“哈哈”字符发送给客户端时,它表示与“ ws:// localhost:3369 /”的WebSocket连接失败:无法将文本框架解码为UTF-8。

the data I send is b'\\x81\\x02\\xe5\\x93\\x88\\xe5\\x93\\x88'. 我发送的数据是b'\\ x81 \\ x02 \\ xe5 \\ x93 \\ x88 \\ xe5 \\ x93 \\ x88'。 \\x81 always this. \\ x81总是这样。 \\x02 means it has two characters and no masks. \\ x02表示它具有两个字符且没有掩码。 \\xe5\\x93\\x88\\xe5\\x93\\x88 represent the paylod('哈哈'). \\ xe5 \\ x93 \\ x88 \\ xe5 \\ x93 \\ x88代表工资单('哈哈')。

Can anyone tell me how to fix this problem, thanks. 谁能告诉我如何解决此问题,谢谢。

js code: js代码:

var socket = new WebSocket('ws://localhost:3369');

socket.onopen = function(){
    console.log('socket open');
    $('#send').click(function(){
        var data = 'dsfg';
        socket.send(data);
        console.log('click');
    });
}

socket.onmessage = function(result){
    console.log("从服务端收到的数据:");
    console.log(result.data);
}

socket.onclose = function(evt){
    console.log('socket close');
}

socket.onerror = function(evt) { 
    console.log('error:')
};

python code: python代码:

def send_data(self, data):
if data:
  data = str(data)
else:
  return False

token = b'\x81'

length = len(data)

if length < 126:
  token += struct.pack('B', length)
elif length <= 0xFFFF:
  token += struct.pack('!BH', 126, length)
else:
  token += struct.pack('!BQ', 127, length)

data = token + data.encode()

self.con.send(data)

return True

The length part must be length in bytes . 长度部分必须为以字节为单位的长度。 So, use 6 as the value of the second byte like below. 因此,使用6作为第二个字节的值,如下所示。

\\x81\\x06\\xe5\\x93\\x88\\xe5\\x93\\x88

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM