我想通过此示例代码向连接并登录服务器的特定用户发送消息,但是我收到此错误:
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),
port = process.env.PORT || 3000,
redis = require("redis"),
redisClient = redis.createClient();
var io_redis = require('socket.io-redis');
io.adapter(io_redis({host: 'localhost', port: 6379}));
io.sockets.on('connection', function (socket) {
socket.on('login', function (data) {
console.log(data.username);
login(data.username, data.password, function (success, value) {
if (success) {
redisClient.set([data.username, socket.id]);
socket.emit('login', {result: true, id: value});
} else {
socket.emit('login', {result: false});
}
});
});
socket.on('message', function (username) {
redisClient.get(username, function (err, socketId) {
io.sockets.connected[socketId].emit('message', 'Hey !!');
});
});
});
为什么我会收到此错误:我搜索并阅读此解决方案的许多页面,但据我所知,我的代码似乎是正确的,但我不知道什么是问题。
错误是针对以下代码行:
io.sockets.connected[socketId].emit('message', 'Hey !!');
答案 0 :(得分:0)
//when you do set, wait for set to finish before doing emit('login')
//also fixed you set, instead of array, to put key and value
redisClient.set(data.username, socket.id, function (err, done) {
if (err) {
//now what?
} else {
socket.emit('login', {result: true, id: value});
}
});
//when you do the get, check exists
redisClient.get(username, function (err, socketId) {
if (io.sockets.connected[socketId]) {
io.sockets.connected[socketId].emit('message', 'Hey !!');
}
});
你有
var socket = require(' socket.io'),
和 function(socket){
所以你定义了两次套接字。那不是很好。