简体   繁体   中英

websocket send Chinese characters

I have a websocket server write by python and a websocket client write by javaScript.

when use English characters like 'hahaha', they can send messages to each other and work well.

when use Chinese characters like '哈哈', the server can recieve the message and I decode the message in python side then work well. 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.

the data I send is b'\\x81\\x02\\xe5\\x93\\x88\\xe5\\x93\\x88'. \\x81 always this. \\x02 means it has two characters and no masks. \\xe5\\x93\\x88\\xe5\\x93\\x88 represent the paylod('哈哈').

Can anyone tell me how to fix this problem, thanks.

js code:

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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