简体   繁体   中英

Nodejs Cannot read property 'emit' of undefined error

I'm trying to send message to specific user on nodejs, then save socket.id and nickname as username into array, then get that to send message, but I get this error:

Cannot read property 'emit' of undefined

This is my code:

var socket      = require('socket.io'),
    express     = require('express'),
    app         = express(),
    server      = require('http').createServer(app),
    io          = socket.listen(server);

    io.sockets.on('connection', function (socket) {

        socket.on('login', function (data) {
            login(data.username, data.password, function (success, value) {
                if (success) {
                    usernames[data.username] = socket.id;
                    socket.emit('login', {result: true, id: value});
                } else {
                    socket.emit('login', {result: false});
                }
            });
        });

        socket.on('requestMoney', function (username) {
            log.info('username: ' + username);
            usernames[username].emit('message', {username: 'Hey !!'});
        });
    });

usernames[username] is undefined for the given username , because of one or more of the following things:

  1. Your given username does not match a data.username connected yet, and/or
  2. You're trying to call emit on an number, not a socket ( usernames[data.username] = socket.id; ), and/or
  3. The usernames object is not in scope when you're trying to use it in the requestMoney event handler.

I'd like to place a wager on #2.

    socket.on('login', function (data) {
        login(data.username, data.password, function (success, value) {
            if (success) {
                usernames[data.username] = socket.id;
                io.sockets.emit('login', {result: true, id: value});
            } else {
                io.sockets.emit('login', {result: false});
            }
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM