jrief / django-websocket-redis

Websockets for Django applications using Redis as message queue
http://django-websocket-redis.awesto.com/
MIT License
896 stars 222 forks source link

websocket.receive: UnicodeError 'ascii' #180

Closed bbaobelief closed 8 years ago

bbaobelief commented 8 years ago

Send Chinese error INFO: websocket.receive: UnicodeError 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

jrief commented 8 years ago

when sending what?

domface commented 8 years ago

I found that upgrading to Python3 solves a lot of these issues, particularly with this library.

bbaobelief commented 8 years ago

@jrief @domface python2.7,django1.8, python manage.py runserver

I try to send the Chinese, the link will be disconnected

09:44:23 sent: 123412341234 09:44:23 received: 123412341234 09:44:31 sent: 中文 09:44:31 system: connection closed, ws://127.0.0.1:81/ws/public?subscribe-broadcast&publish-broadcast&echo

log [2016-04-07 09:52:19,203 websocket] INFO: websocket.receive: UnicodeError 'ascii' codec can't decode byte 0xe4 in position 35: ordinal not in range(128)

yguarata commented 8 years ago

@bbaobelief a workaround for this is to convert your string into char codes before sending messages (using String.charCodeAt), and convert it back when you receive a message from the websocket (using String.fromCharCode). This is ugly but solves the issue:

function to_char_code(str) {
    var char_codes = [];
    for (var i=0; i < str.length; i++) {
        char_codes.push(str.charCodeAt(i));
    }
    return char_codes;
}

function from_char_code(char_codes) {
    var str = "";
    for (var i=0; i < char_codes.length; i++) {
        str += String.fromCharCode(char_codes[i]);
    }
    return str;
}

Note that you can use JSON.stringify to convert the char codes array into string and vice versa, if necessary.

bbaobelief commented 8 years ago

@yguarata Thanks, I am now using JS to solve the problem,

var classObj= { ToUnicode:function(str) { return escape(str).replace(/%/g,"\").toLowerCase(); }, UnUnicode:function(str) { return unescape(str.replace(/\/g, "%")); } }