For more intricate systems, it is common to create a custom client object that maintains a record of all connected users and the rooms they are currently in. This can also serve as a way to represent the current state of users on the server. I recommend using a Map();
for this purpose, where the socket.id is set as the key and the clients object is the value.
A simple approach to building this could be;
Client.js
// JavaScript source code
var client = function client(socket) {
this.id = socket.id;
this.state = "newly Connected";
this.clientSocket = socket;
this.LobbyArr = [];
this.changeState = function (newState) {
this.state = newState;
}
this.addLobby = function (lobbyId) {
this.LobbyArr.push(lobbyId);
}
}
module.exports = Client;
Server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//loading server side modules
var Client = require('../Client.js');
//Gets all of the connected clients
var allConnectedClients = new Map();
io.on('connection', function (socket){
var connectedUser = new Client(socket);
allConnectedClients.set(socket.id, connectedUser);
});
The code above looks for an opponent, but if none is found, the user should wait for others.
Expanding on the example, by setting states for connected clients, we can loop through the map to identify where the user currently is based on this.state
. If no suitable user is found, a new message can be emitted to the client.
What is the best way to check if a player is already playing?
To determine if a player is already playing, you can simply check the user's current state
.
When a user joins a room, their default room is not removed.
In socket.io, each user is automatically placed into their own default room upon connecting to the server, so the default room will not be deleted.