socket.emit中包含特殊字符的错误

时间:2017-11-13 16:12:11

标签: node.js sockets

首先,对不起,如果我的英语不是很好。

我正在尝试使用socket.io:

在nodeJS中进行聊天
  • 用户向节点服务器发送消息,并将消息正确发送给所有连接的客户端。

  • 消息保存在“历史”变量中,因此新连接可以查看所说的内容。

问题是当一个特殊字符存储在历史变量中时,例如“¿”。

源代码(服务器):

var io = require('socket.io')(3333);

var historico_mensajes = [];

console.log('Iniciando aplicacion');

io.on('connection',function(socket) {
    console.log('Nueva conexion');
    console.log(historico_mensajes);

    socket.emit("chat_hist",{ historico_mensajes });

    socket.on('chat_msg',function(data){
        console.log("Msg no escapado: "+data.msg);
        if(data.msg.length>150) {
            socket.emit('sv_chat_msg', {
                type: 'error',
                msg: 'too long'
            });
        } else {
            io.sockets.emit('sv_chat_msg', {
                type: 'chat',
                msg: data.msg,
                name: 'Test name',
                icon: 'Test icon',
                user: 'Test user',
                rank: 'Test rank'
            });
            historico_mensajes.push({
                    type: 'chat',
                    msg: data.msg,
                    name: 'Test name',
                    icon: 'Test icon',
                    user: 'Test user',
                    rank: 'Test rank'
            });
            if(historico_mensajes.length > 15) { historico_mensajes.splice(0,1); }

        }
    });
});

源代码(客户端):

var HOST = "http://127.0.0.1:3333";
var SOCKET = null;

$(document).ready(function() {
    connect();
});

function connect() {
    if (!SOCKET) {
        console.log("Connecting to server...");
        SOCKET = io(HOST);
        SOCKET.on('connect', function() {
            console.log("Established connection!");
        });
        SOCKET.on('chat_hist', function(m=null) {
            console.log("chat hist recibido");
            console.log(m);
            /*
            if(m) {
                for (var ms = 0; ms < m.historico_mjs.length; ms++) {
                    chat("user", m.historico_mjs[ms].name, m.historico_mjs[ms].msg, m.historico_mjs[ms].icon, m.historico_mjs[ms].rank);
                }
            } else {
                console.log("no historico");
            }
            */
        });     
        SOCKET.on('sv_chat_msg', function(data) {
            console.log("mensaje del server recibido para el usuario");
            switch(data.type) {
                case "error":
                    chat('bot_errors','Test Bot',data.msg);
                    break;
                case "chat":
                    chat('user',data.name,data.msg,data.icon,data.rank);
                    break;
                default:
                    chat('bot','Test Bot','Unknow msg');
                    break;
            }
        });
    }
}

if (!String.prototype.format) {
    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };
}

function chat(tipo,name,msg,avatar,rank){
    var toChat = "";
    if(msg && name) {
        msg = msg.replace(/(<|>)/g, '');
        name = name.replace(/(<|>)/g, '');
        switch(tipo) {
            case "bot":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">100</span><a href="#" data-show-profile="001"><img width="18px" src="images/crown.png" alt="user snap" /><em style="color:#ff8b00;">'+name+'</em></a></header><div class="text" style="color:#ff9800;">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
            case "bot_errors":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">100</span><a href="#" data-show-profile="001"><img width="18px" src="images/crown.png" alt="user snap" /><em style="color:#ff8b00;">'+name+'</em></a></header><div class="text" style="color:#a94442;">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
            case "user":
                toChat='<li><div class="comment-box"><header class="header"><span class="cmt-user-level">'+rank+'</span><a href="#" data-show-profile="001"><img width="18px" src="'+avatar+'" alt="user snap" /><em>'+name+'</em></a></header><div class="text">'+msg+'</div><span class="remove-comment"><i class="flaticon-remove-user"></i></span></div></li>';
                break;
        }

        $("#chatArea").append(toChat);
    }
}

示例:

当我发送普通字符时,一切正常:

enter image description here

如果按F5并通过聊天获取数组:

enter image description here

但是......如果我用“¿”charset发送消息:

enter image description here

如果现在我按F5 ......会发生这种情况:

enter image description here

我该怎么办?

1 个答案:

答案 0 :(得分:0)

在代码运行后按F5:

# predicting the angle (in radians)
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import r2_score
# generate toy data
np.random.seed(1)
X = np.random.normal(size=(100, 2))
y = np.arctan2(np.dot(X, [1,2]), np.dot(X, [3,0.4]))
# simple prediction
model = MLPRegressor(random_state=42, activation='tanh', max_iter=10000)
y_simple_pred = cross_val_predict(model, X, y)
# transformed prediction
joint = cross_val_predict(model, X, np.column_stack([np.sin(y), np.cos(y)]))
y_trig_pred = np.arctan2(joint[:,0], joint[:,1])
# compare
print(r2_score(y, y_simple_pred)) # R^2 about 0.53
print(r2_score(y, y_trig_pred))   # R^2 about 0.85

完成上面的代码并将历史记录放在屏幕上。请使用与上面类似的代码来获得结果。