javascript - Nodejs send to specific user get Cannot read property 'emit' of undefined error -
i want send message specific user connected , logging server sample code, error:
cannot read property 'emit' of undefined
this below code sample 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 error: search , read many pages of solution far know code seemd correct, don't know whats problem.
error line of code:
io.sockets.connected[socketid].emit('message', 'hey !!');
- not sure why didn't provide line number failed. have multiple emits.
- who says socket there when redis finishes? must check if exists.
//when set, wait set finish before doing emit('login') //also fixed set, instead of array, put key , value redisclient.set(data.username, socket.id, function (err, done) { if (err) { //now what? } else { socket.emit('login', {result: true, id: value}); } });
//when get, check exists redisclient.get(username, function (err, socketid) { if (io.sockets.connected[socketid]) { io.sockets.connected[socketid].emit('message', 'hey !!'); } });
you have
var socket = require('socket.io'),
and function (socket) {
so defined socket twice. thats not great.
Comments
Post a Comment