我也遇到了这个问题,这是我的解决方案,就垃圾邮件发出去(恶意套接字使用)..
var spamData = new Object();
var spamCheckFunctions = ["updateUsers","moreEmits"]; // anti-spam will check these socket emits
var antiSpam = 3000; // anti spam check per milliseconds
var antiSpamRemove = 3; // -spam points per antiSpam check
var maxSpam = 9; // Max spam points before disconnect is thrown to the socket
io.sockets.on('connection', function (socket) {
// Spam Check, this binds to all emits
var emit = socket.emit;
socket.emit = function() {
data = Array.prototype.slice.call(arguments);
if(spamCheckFunctions.contains(data[0])){
addSpam(socket);
};
emit.apply(socket, arguments);
};
var $emit = socket.$emit;
socket.$emit = function() {
data = Array.prototype.slice.call(arguments);
if(spamCheckFunctions.contains(data[0])){
addSpam(socket);
}
$emit.apply(socket, arguments);
};
});
function maxSpamCheck(socket){
if(spamData[socket.username].spamScore>=maxSpam && !socket.spamViolated){
socket.spamViolated = true;
socket.disconnect();
}
}
function checkSpam(){
for(user in spamData){
if(spamData[user].spamScore>=1) spamData[user].spamScore-=antiSpamRemove;
}
return;
}
setInterval(checkSpam,antiSpam);
function addSpam(socket){
if(socket.spamViolated) return;
spamData[socket.username].spamScore+=1;
maxSpamCheck(socket);
}
// Then add this where your user is authenticated
function authenticate(socket){
socket.username = username // here you define username
socket.spamViolated = false;
spamData[socket.username] = {
spamScore: 0
}
}
Array.prototype.contains = function(k) {
for(var p in this)
if(this[p] === k)
return true;
return false;
};
基本上绑定到所有发射并检查发射名称是否包含在spamCheckFunctions
如果它是它会添加一个垃圾邮件点,如果用户超过垃圾邮件分数量(maxSpam
); 他将断开连接。并且对于任意定义的每毫秒antiSpam
减去定义的用户垃圾邮件分数antiSpamRemove
我确信有更清洁的解决方案,但这个解决方案对我来说非常好:)
只需确保验证/验证用户。
这就是我对它们进行身份验证的方式(不使用 nodejs 作为网络服务器,而是使用 django):
io.configure(function(){
io.set('authorization', function(data, accept){
if(data.headers.cookie){
data.cookie = cookie_reader.parse(data.headers.cookie);
return accept(null, true);
}
return accept('error', false);
});
});
现在您可以访问socket.handshake.cookie['sessionid']
(在我的情况下,这与 django 一起使用)然后与socket.handshake.cookie['sessionid']
您的会话存储在网络服务器上的条目匹配