Nodejs无法读取未定义错误的属性'emit'

[英]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:

我正在尝试向nodejs上的特定用户发送消息,然后将socket.id和昵称作为用户名保存到数组中,然后将其发送给发送消息,但是我收到此错误:

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 !!'});
        });
    });

2 个解决方案

#1


1  

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

用户名[username]未定义给定用户名,因为有以下一项或多项内容:

  1. Your given username does not match a data.username connected yet, and/or
  2. 您的用户名与已连接的data.username不匹配,和/或

  3. You're trying to call emit on an number, not a socket (usernames[data.username] = socket.id;), and/or
  4. 你试图在一个数字上调用emit,而不是socket(usernames [data.username] = socket.id;)和/或

  5. The usernames object is not in scope when you're trying to use it in the requestMoney event handler.
  6. 当您尝试在requestMoney事件处理程序中使用它时,usernames对象不在范围内。

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

我想赌#2。

#2


0  

    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});
            }
        });
    });

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/08/87ff1295b471a0e42d705f7d2505b2c2.html



 
  © 2014-2022 ITdaan.com