简体   繁体   中英

Nodejs send to specific user get Cannot read property 'emit' of undefined error

i want to send message to specific user which connected and logging into server by this sample code, but i get this error:

Cannot read property 'emit' of undefined

this below code is my sample to test:

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

why i get this error: i search and read many pages of this solution but as far as i know my code seemd correct, but i don't know whats problem.

error is for this line of code:

io.sockets.connected[socketId].emit('message', 'Hey !!');
  1. not sure why you didn't provide the line number that failed. you have multiple emits.
  2. who says the socket is there when redis get finishes? you must check if exists.

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

  1. you have

    var socket = require('socket.io'),

and function (socket) {

so you defined socket twice. thats not great.

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