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);
}