[英]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
和nickname
作为用户名保存到数组中,然后获取该消息以发送消息,但是出现此错误:
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: 由于以下一项或多项原因,未为给定的
username
定义usernames[username]
:
username
does not match a data.username
connected yet, and/or username
与data.username
尚未匹配,和/或 emit
on an number, not a socket ( usernames[data.username] = socket.id;
), and/or emit
上一个号码而不是一个插座( usernames[data.username] = socket.id;
和/或 usernames
object is not in scope when you're trying to use it in the requestMoney
event handler. requestMoney
事件处理程序中使用usernames
对象时,该对象不在范围内。 I'd like to place a wager on #2. 我想下注#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});
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.