Mahmoud Niypoo
Mahmoud Niypoo

Reputation: 1710

socket.io emitted from one id

I did code by nodejs and angular4 with socket.io I have been used 2 different browsers and I have checked connection and socket.io has gave 2 different socket.id but when emit the 2 browsers emitted from 1 id !

code in app.js

io.on('connection', function(socket){app.set('socket', socket);console.log('a user connected to :'+socket.id);socket.on('disconnect', function(){console.log('user disconnected');});});

code emit

        let socket     = req.app.get('socket');
        console.log('emit from :' +socket.id )
        socket.emit('chatroom-'+chat.room, chat);

code listen in client side

        this.socket.on('chatroom-'+this.roomData._id, (data)=>{
          console.log('socket push',data);             
        })

all my code

initialize socketio at app.js

//construct
const express       = require('express');
const app           = express();
const server        = require('http').createServer(app);
const io            = require('socket.io').listen(server);
const port          = 3000;

//initialize
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname,'public')));
///passport strategy
require('./config/passport');

//routes
const chat    = require('./routes/chat');
app.use('/chat',chat);


io.on('connection', function (socket) {
    app.set('socket', socket);
    console.log('a user has connected as :'+socket.id);
    io.on('connection', function () {
        console.log('a user has disconnected ');
    });

});

//start server code
server.listen(port, ()=> {
    console.log('node serve has been started on port : '+port);
})

emit chat after add new message at chat.js route

///add new chat
router.post('/add', passport.authenticate('jwt',{session:false}), (req,res,next) => {
    //validation
    if(!req.user._id){ res.json({status:false, message:'something went wrong, please sign-in first and try again'}) }
    if(req.user._id != req.body.user){ res.json({status:false, message:'something went wrong, please sign-in first and try again'}) }
    if(!req.body.room){ res.json({status:false, message:'something went wrong, please refresh the page and try again'}) }
    if(!req.body.text){ res.json({status:false, message:'you have to fill a chat message to add it'}) }
    next();
}, (req, res) => {
    //create new one 
    let chatData = new Chat(req.body);

    //do create
    Chat.create(chatData, (err, chat)=>{
        //error 
        if(err){ res.josn({status:false, message:err.message})}
        else{
            //replace user id to user data
            chat.user = req.user;
            //define socketio
            let socket     = req.app.get('socket');
            //emit new message
            socket.broadcast.emit('chatroom-'+chat.room, chat);
            //return respone
            res.json({status:true, message:'the message has been sent', chat:chat})
        }
    })
});

Upvotes: 0

Views: 815

Answers (1)

jfriend00
jfriend00

Reputation: 707446

If you're just trying to broadcast to a room from your route, you can change this:

io.on('connection', function (socket) {
    app.set('socket', socket);
    console.log('a user has connected as :'+socket.id);
    io.on('connection', function () {
        console.log('a user has disconnected ');
    });
});

to this:

// make io available via app object
app.set('io', io);

io.on('connection', function (socket) {
    console.log('a user has connected as :'+socket.id);
    io.on('disconnect', function () {
        console.log('a user has disconnected ');
    });
});

And, change this:

        let socket     = req.app.get('socket');
        //emit new message
        socket.broadcast.emit('chatroom-'+chat.room, chat);

to this:

        let io  = req.app.get('io');
        //emit new message
        io.emit('chatroom-'+chat.room, chat);

This will consistently send the chat to all users in the room.


If you want to send only to the other users in the room, not to the user who originated the message, then it will be easier if you send the message over socket.io, not via a form post. Then, you can just use:

 socket.broadcast.emit('chatroom-'+chat.room, chat);

where socket is the socket that you received the message on over socket.io which you will have nice and handy.

Upvotes: 1

Related Questions