回调函数socket.io + Node.js的
问题描述:
有一个客户端和服务器端代码:回调函数socket.io + Node.js的
客户:
socket.on('connect', function() {
showSystemMessage('Connected.');
socket.emit('setuser', wm, function(data){
console.log(data);
socket.emit('whoisonline', wm, function(data){
getOnlineFriends(data);
});
});
});
服务器:
io.on('connection', function(socket) {
socket.on('setuser', function (data, cb) {
cb(data);
});
});
我得到错误:
TypeError: undefined is not a function on line 18
第18行:
socket.on('setuser', function (data, cb) {
cb(data); // Line 18
});
然后我想你的解决方案,我得到:
TypeError: undefined is not a function in line 35
socket.on('whoisonline', function (data, cb) {
redis.sinter('user.friend:' + data.id, 'onlineusers', function(error, intersection) {
friends.online = intersection;
friends.total = intersection.length;
if(friends.total > 0){
intersection.forEach(function(entry) {
var socketid = clients[entry];
io.sockets.connected[socketid].emit('in', { id : data.id, total : friends.total });
});
}
cb(friends); // Line 35
});
});
答
Socket.io不回调的工作,你有.emit工作()和.on()。在这种情况下你的源代码看起来像:
客户:
socket.on('connect', function() {
showSystemMessage('Connected.');
socket.emit('setuser', wm);
socket.on("setuser", function(data){
console.log(data);
socket.emit('whoisonline', wm);
socket.on("whoisonline", function(data) {
getOnlineFriends(data);
});
});
});
服务器:
io.on('connection', function(socket) {
socket.on('setuser', function (data) {
socket.emit("setuser", data);
});
});
嗯,谢谢你,似乎工作,但我得到回调againn重写后在你的代码上。编辑问题 – AhmedFaud 2014-11-06 15:23:37
@AhmedFaud用'socket.emit(“whoisonline”,friends)替换第35行;'' – 2014-11-06 15:35:58