我试图通过建立一个谁可以先按下按钮的小游戏来学习nodeJs,
当用户加入那里时,推入名为" room"的数组,其中包含用户名和分数,然后广播给所有连接的客户端,让他们知道房间里的人
room.push({userName:userName,score:0});
var userName_json = JSON.stringify({ type:'userName', data: userName });
broadcastMessage(userName_json);
广播它们会向页面添加一个html元素
connection.onmessage = function (message) {
if (json.type === 'userName') {
addUser(json.data);
}
function addMessage(userName) {
$('#' + userName).addClass('green');
console.log(userName + 'hits first');
}
当用户断开与节点服务器的连接时,需要将其从此会议室中删除
connection.on('close', function(connection) {
if (userName !== false) {
console.log('user name is not false lets splice');
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
clients.splice(index, 1);
room.splice(index, 1);
var userName_json = JSON.stringify({ type:'retire', data: userName });
broadcastMessage(userName_json);
} else {
console.log('cant do anything userName is false');
}
});
删除用户html元素
connection.onmessage = function (message) {
else if (json.type === 'retire') {
console.log(json);
retireUser(json.data);
}
function retireUser(userName) {
$('#' + userName).remove();
console.log(userName + ' cant handle the pressure');
}
现在,如果用户加入房间然后离开,如果用户与已经在场的人加入房间,或者用户加入他们然后他们尝试离开用户并不总是从房间阵列中移除,或者仍然连接的人从页面中删除了html元素。
关于什么错误的想法?
答案 0 :(得分:1)
我使用map / object来存储key / val数据而不是数组。
next_uid = 0;
users = {};
wsserver.on('connection', function (conn) {
conn.user_id = ++new_uid; // you can store user-ID here
users[conn.user_id] = { /* any user data you want */ }
conn.on('message', function (message) {
console.log('message form ' + conn.user_id);
});
conn.on('close', function (code, reason) {
console.log(conn.user_id + ' disconnected');
delete users[conn.user_id];
});
}
答案 1 :(得分:0)
我发现的一个问题是here;你不能假设索引保持不变。如果删除了具有较小索引的不同连接,则上述所有索引都会移位-1。你必须找出索引when you remove:
val userProducts: RDD[(String, Long)] =
userProductRDD.filter(_._3 == 1) // buys only
.map { case (u, p, _, _) => (u, p) } // drop buys and price
.distinct // keep distinct (user, product)
.map { case (u, _) => (u, 1L) } // word count problem
.reduceByKey(_ + _)
// similarly
val productUsers: RDD[(Long, Long)] =
userProductRDD.filter(_._3 == 1)
.map { case (u, p, _, _) => (p, u) }
.distinct
.map { case (p, _) => (p, 1L) }
.reduceByKey(_ + _)
我还认为将用户名用作html ID并不是一个好主意,特别是如果它们可以包含空格。相反,您应该为每个用户分配一个唯一的编号作为ID。