Socket.io如何向任何人发送消息?

时间:2022-11-17 07:37:21

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).

我正在用socket.io做我的第一个应用程序,我想向任何用户发送消息。我知道广播功能,但我想向任何人发送消息。我已经找到并且有一种方法:使用io.sockets.emit,但我不知道在哪里编写该代码因为我在node.js上使用express而且我在我的函数中接收了一个socket(当前用户)。

Thank you.

2 个解决方案

#1


1  

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

这是一个聊天的例子。完整代码是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

希望它对你有所帮助。附:它使用房间。所以,如果你想向所有用户发送消息。将io.sockets.in(room).emit更改为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)});

                });
            });

#2


0  

Sure: simply,

keep your socket connections in your app.js or server.js file.

将套接字连接保存在app.js或server.js文件中。

simply follow the code:

只需按照代码:

var http = require('http').Server(app);
var io = require('socket.io')(http);

now start the connection like:

现在开始连接像:

io.on('connection', function(socket){
console.log("A user connected");
}):

whenever you run the server file, "a user connected" will be printed. means, one client has connected to the server.

无论何时运行服务器文件,都将打印“用户已连接”。表示一个客户端已连接到服务器。

to disconnect to the server: io.on('connection', function(socket){ console.log("A user connected");

断开与服务器的连接:io.on('connection',function(socket){console.log(“用户连接”);

    socket.on('disconnect',function(){
    console.log("a user disconnected");
    });
}):

now you are ready to send a message to all who are connected to the server:

现在您已准备好向所有连接到服务器的人发送消息:

 socket.on('chat message', function(data){
 socket.emit('chat message', msg);
 });

If you want send a message to all exclude sender:

如果要向所有排除发件人发送邮件:

socket.on('chat message', function(data){
 io.broadcast.emit('chat message', msg);
 });

For more reference: Send response to all clients except sender (Socket.io)

有关更多参考:发送响应除发件人之外的所有客户端(Socket.io)

I hope u got an idea on it.!! Good luck

我希望你对它有所了解。!!祝好运

#1


1  

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

这是一个聊天的例子。完整代码是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

希望它对你有所帮助。附:它使用房间。所以,如果你想向所有用户发送消息。将io.sockets.in(room).emit更改为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)});

                });
            });

#2


0  

Sure: simply,

keep your socket connections in your app.js or server.js file.

将套接字连接保存在app.js或server.js文件中。

simply follow the code:

只需按照代码:

var http = require('http').Server(app);
var io = require('socket.io')(http);

now start the connection like:

现在开始连接像:

io.on('connection', function(socket){
console.log("A user connected");
}):

whenever you run the server file, "a user connected" will be printed. means, one client has connected to the server.

无论何时运行服务器文件,都将打印“用户已连接”。表示一个客户端已连接到服务器。

to disconnect to the server: io.on('connection', function(socket){ console.log("A user connected");

断开与服务器的连接:io.on('connection',function(socket){console.log(“用户连接”);

    socket.on('disconnect',function(){
    console.log("a user disconnected");
    });
}):

now you are ready to send a message to all who are connected to the server:

现在您已准备好向所有连接到服务器的人发送消息:

 socket.on('chat message', function(data){
 socket.emit('chat message', msg);
 });

If you want send a message to all exclude sender:

如果要向所有排除发件人发送邮件:

socket.on('chat message', function(data){
 io.broadcast.emit('chat message', msg);
 });

For more reference: Send response to all clients except sender (Socket.io)

有关更多参考:发送响应除发件人之外的所有客户端(Socket.io)

I hope u got an idea on it.!! Good luck

我希望你对它有所了解。!!祝好运