0
\$\begingroup\$

I'm creating a 2-player online game using Node.js with Express and Socket.IO

My task is to create a new room when 1st, 2nd, etc ... rooms are full. From this article I know how to create one room for all connections:

// require everything you need
var io = require('socket.io').listen(server);
io.on('connection',function(socket){
    // creating socket.player with unique ID
    socket.on('anyeventfromconnectedplayer', function doSomething () {...
    });
});

How to create new rooms for new play sessions?

Socket.IO has a mechanism to implement the thing I need but I don't understand how to use it correctly.

\$\endgroup\$
2
\$\begingroup\$

I would suggest not using Socket.IO's rooms mechanism. It is not very flexible and isn't very appropriate for a robust server architecture.

Here's a quick scribble of how you could structure your rooms on the server. Obviously you'll want to use your own class for Player instead of the socket object, lookup rooms by id etc, but I wanted to keep the example short.

function Server(io) {
    this.players = {}
    this.rooms = []

    io.on('connection', (socket) => {
        let player = this.players[socket.id] = socket

        let openRoom = this.findOrCreateRoom()
        openRoom.players.push(player)
        player.currentRoom = openRoom

        player.on('playerAction', (msg) => this.routeMsgToRoom(msg, player))
    })
}

Server.prototype.routeMsgToRoom = function(msg, player) {
    if (!player.currentRoom) throw `Player ${player.id} is not in a room!`

    player.currentRoom.handlePlayerMsg(msg, player)
}

Server.prototype.findOrCreateRoom = function() {
    let room = _.find(this.rooms, r => r.players.length < 2)
    if (!room) {
        room = new Room()
        this.rooms.push(room)
    }
    return room
}


function Room() {
    this.players = []
}

Room.prototype.handlePlayerMsg = function(msg, player) {
    //do something
    _.each(this.players, p => p.emit('actionHappened', { roomData: 42 }))
}
\$\endgroup\$
2
  • \$\begingroup\$ Thank you ! I got a couple of questions . What are those : let room = _.find(this.rooms, r => r.players.length < 2) _.each(this.players, p => p.emit('actionHappened', { roomData: 42 }) doing ? \$\endgroup\$ – Vitozz_RDX Aug 1 '18 at 20:01
  • 1
    \$\begingroup\$ Oh, it's the lodash utility library. That line just searches for the first room with less than 2 players. The _.each line just sends the room update to all the players in the room \$\endgroup\$ – Kal_Torak Aug 1 '18 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.