Daniel 976034 Daniel 976034 - 1 month ago 12
Node.js Question

Socket.io how to send a message to anyone?

I'm doing my first app with socket.io and I want to send a message to any user. I know broadcast function, but I want to send a message to ANYONE. I've seeked and there's a way: using io.sockets.emit, but I don't know where I have to write that code because I'm using express on node.js and I receive in my function a socket (the current user).

Thank you.

Answer

Here is a example of chatting. full codes are https://github.com/bwcho75/node.js_study/tree/master/node_chatting

Hope it to helpful to u. P.S. it uses room. So if u want to send message to all user. Change io.sockets.in(room).emit to io.sockets.emit

        var express = require('express');
        var routes = require('./routes');
        var http = require('http');
        var path = require('path');

        var app = express();
        app.use(express.bodyParser());
        app.use(express.cookieParser('your secret here'));
        app.use(express.session());
        app.use(express.static(path.join(__dirname, 'public')));
        app.set('views', path.join(__dirname, 'views'));
        app.set('view engine', 'ejs');
        app.use(express.favicon());
        app.use(express.logger('dev'));
        app.use(express.json());
        app.use(express.urlencoded());
        app.use(express.methodOverride());
        app.use(app.router);

        var httpServer =http.createServer(app).listen(3000, function(req,res){
            console.log('Socket IO server has been started');
        });
        // upgrade http server to socket.io server
        var io = require('socket.io').listen(httpServer);

        var count = 0;
        var rooms = new Array() ;

        app.get('/:room',function(req,res){
            console.log('room name is :'+req.params.room);
            res.render('index',{room:req.params.room});
        });



        io.sockets.on('connection',function(socket){

            socket.on('joinroom',function(data){
                socket.join(data.room);

                socket.set('room', data.room,function() {
                    var room = data.room;
                    var nickname = '손님-'+count;

                    socket.emit('new', {nickname: nickname});

                    // Create Room
                    if(rooms[room] == undefined ){
                        console.log('room create :'+room);
                        rooms[room] = new Object();
                        rooms[room].nicknames = new Object();
                        rooms[room].socket_ids = new Object();
                    }

                    // Store current user's nickname and socket.id to MAP
                    rooms[room].socket_ids[nickname] = socket.id
                    rooms[room].nicknames[socket.id] = nickname;

                    // broad cast join message
                    data = {msg : nickname +' 님이 입장하셨습니다.'};
                    io.sockets.in(room).emit('broadcast_msg',data);

                    // broadcast changed user list in the room
                    io.sockets.in(room).emit('userlist',{users:Object.keys(rooms[room].socket_ids)});
                    count++;
                });

            });

            socket.on('changename',function(data){
                socket.get('room',function(err,room){
                    var nickname = data.nickname;
                    // if user changes name get previous nickname from nicknames MAP
                    var previous_nickname = rooms[room].nicknames[socket.id];
                    if(previous_nickname != undefined){
                        delete rooms[room].socket_ids[previous_nickname];
                    }
                    rooms[room].socket_ids[nickname] = socket.id
                    rooms[room].nicknames[socket.id] = nickname;

                    data = {msg : previous_nickname +' 님이 '+nickname+'으로 대화명을 변경하셨습니다.'};
                    io.sockets.in(room).emit('broadcast_msg', data);

                    // send changed user nickname lists to clients
                    io.sockets.in(room).emit('userlist',{users:Object.keys(rooms[room].socket_ids)});

                });
            });