1

I am creating an application in which users interact in pairs. Once a user signs in, he is automatically connected to a Socket.io room containing only one person, or if all rooms are full, create a new room based on his user id.

I'm having a hard time because it seems that socket.io is creating rooms based on socket id number, but not creating the rooms based on user id number specified by me. Also, it's hard to test because I'd need to log in as two users.

server/socket.js:

module.exports = function (io) {
    io.sockets.on('connection', function (socket) {
        socket.emit('message', {message: "Waiting for player..."})
        socket.on('create', function (newRoom) {
            var rooms = io.sockets.adapter.rooms;
            var clients = function (rm) {
                return io.of('/').adapter.rooms[rm];
            };

            // if any of the current rooms have only one
            // player, join that room.
            for (room in rooms) {
                console.log(room)
                if (Object.keys(clients(room)).length == 1) {
                    socket.join(room);

            } else {
                socket.join(newRoom);
            }
        }
    })
    })

}

client/sockets.js:

window.onload = function () {
    var socket = io.connect('http://localhost:3700');
    var messageBox = document.getElementById('message_box');

    socket.on('message', function (data) {

            console.log(data);
            console.log(data.message);
            messageBox.innerHTML = data.message;


    });

    socket.emit('create', 'ROOM: ' + loggedInUser._id);
}
Cameron Sima
  • 5,086
  • 6
  • 28
  • 47
  • So what's your question? (also mind to add socket.io version you're using) – Kirill Slatin Aug 13 '15 at 00:22
  • I'm using the latest version. I guess i just need some pointers and guidance on how to make this work as i can't quite wrap my mind around it – Cameron Sima Aug 13 '15 at 04:32
  • Rooms are not _created_ explicitly. You just `.join(newRoomName)` and that does the job. Also namespaces are nothing to do with rooms. I see `of('/')` usage however don't see any significant influence from it... So I don't see any issues in code from just looking at it. You might need to debug it and watch if rooms are joined properly. I am not sure about using `:` in room's name, but I doubt that is an issue... – Kirill Slatin Aug 13 '15 at 05:39
  • Thanks. One problem is that a room named 'ROOM: ID ' is never joined – Cameron Sima Aug 13 '15 at 15:55
  • Before continuing I would remove all spaces and colon from the room identifier to make sure this is not an issue – Kirill Slatin Aug 13 '15 at 18:20

0 Answers0