gpt4 book ai didi

javascript - 回调函数socket.io + node.js

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:59 24 4
gpt4 key购买 nike

有客户端和服务器端代码:

客户:

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.on('setuser', (name, cb) => { cb(name); });
  • 在客户端

    socket.emit('setuser', 'user data', r => { console.log(r); });

关于javascript - 回调函数socket.io + node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26782665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com