Socketio广播到选定的socket.id而不是使用房间和命名空间socket.io

时间:2017-05-30 18:56:33

标签: node.js socket.io

我正在尝试实现一个小型聊天应用程序,用户可以将消息发送到特定的Id或Id的集合。我浏览了socketio文档并找到了合适的解决方案。我试过这个功能

socket.broadcast.to(socketid).emit('message', 'for your eyes only');

但它没有用。

    let onlineUsers = [];
    let sockets = {};

    module.exports = function (io,app) {

      io.on('connection', (socket) => {

            // Event for user connecting to socket
            socket.on('online', (data) => {
              if(data.username!=null){
                socket.name = data.username;
                onlineUsers.push(data.username);
                sockets[data.username] = socket.id;
                console.log(data.username+' online');
              }
            });

            socket.on('Chat', (data) => {
                socket.broadcast.to(sockets[data.receiver]).emit('message',data.message);
                socket.leave(name);
                console.log('message sent');
            });

    // Event for user going ofline
    socket.on('offline', () => {
        for (var i = 0, len = onlineUsers.length; i < len; i++) {
            if (onlineUsers[i] && onlineUsers[i].username === socket.name) {
                onlineUsers.splice(i, 1);
                delete sockets[socket.name];
                socket.broadcast.emit('offline', {
                    username: socket.name
                });
            }
        }
        console.log('offline');
    });    
}

2 个答案:

答案 0 :(得分:0)

我这样做(复制并从生产中改变一点,我希望没有重要的东西丢失,它就像那样)

user = [];

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

    user[socket.id] = socket;

    //to send to a group of users which fit with criteria whatever
    socket.on('chatroom1',function(){
        socket.join('chatroomONE');
        io.to('chatroomONE').emit('connections', count_connections);
    });


    socket.on('disconnect', function(data){
        delete user[socket.id];
    });

    socket.on('messagetosb', function(msg){
        var clientid = ""; //here your code to get the client from the users array to whom you want to send a message
        socket.broadcast.to(clientid).emit('antwort', "message x y z");
    });

});

答案 1 :(得分:-1)

考虑以下内容:

SELECT col1
FROM (SELECT * 
      FROM (SELECT text1 as col1, 1 as ord, @rn:=@rn+1 as RN
            FROM xtabla2
            CROSS JOIN (SELECT @rn:=0) rn
            ORDER BY text1) col1
      UNION ALL
      SELECT * 
      FROM (SELECT text2, 2, @rn2:=@rn2+1
            FROM xtabla2
            CROSS JOIN (SELECT @rn2:=0) rn
            ORDER BY text2) col2
      UNION ALL
      SELECT * 
      FROM (SELECT text3, 3, @rn3:=@rn3+1
            FROM  xtabla2
            CROSS JOIN (SELECT @rn3:=0) rn3
            ORDER BY text3) col3
      ) OneCol
ORDER BY ord, RN

当然,你可以使用除id以外的东西......但是你明白了。