I'm making a multiplayer game that is using websockets to share the gamestate between all the connected players.
I decided to use socket.io with koa and now I'm facing the following problem.
First when a user connects to the server a new player is created.
const playersMeta = {}
io.on('connect', socket => {
const playerId = uniqid() // Creates a new unique id for a player
playersMeta[socket.id] = { playerId } // Stores the players id using the socket.id as key
socket.on('disconnect', () => {
delete playersMeta[playerId]
})
})
The thing is that a player needs to know the unique id that the server assigned to it. The reason is that there is a game state that tells every connected player where all the entities are. The camera follows the player that was created when you enter the game, that's why I need to know which player the camera should follow.
I can create a new socket.io event, an then the player emits an event that returns the id that you want but it looks like is getting too much complicated.
Events are nice to sync between different clients, in real time, data that need too change but I'm sure that the id of the player is not going to change.
Maybe is better to just create an api rest endpoint to get this data. I'm using Koa and I'm not sure if I can use the same websocket connection instead of using http.
Can't you just emit it to the same socket?
const playersMeta = {}
io.on('connect', socket => {
const playerId = uniqid() // Creates a new unique id for a player
playersMeta[socket.id] = { playerId } // Stores the players id using the socket.id as key
socket.emit('connected', { serverId: 'foo'});
socket.on('disconnect', () => {
delete playersMeta[playerId]
})
});
And on your client:
var socket = io('http://server');
socket.on('connected', function (data) {
console.log(data); // { serverId: 'foo'}
// do whatever you want with the servid
});