我正在尝试向nodejs上的特定用户发送消息,然后将socket.id
和nickname
作为用户名保存到数组中,然后将其发送给发送消息,但我收到此错误:
Cannot read property 'emit' of undefined
这是我的代码:
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 !!'});
});
});
答案 0 :(得分:1)
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
未定义给定的usernames[username]
:
username
与已连接的username
和/或data.username
,而不是套接字(emit
)和/或usernames[data.username] = socket.id;
事件处理程序中使用usernames
对象时,requestMoney
对象不在范围内。我想打赌#2。
答案 1 :(得分:1)
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});
}
});
});