I have the following code on the server:
var game = io.listen(app);
game.sockets.on('connection', function(socket){
storePlayers(socket.id);
//Only the player the connects gets this message
socket.emit('firstTime', {message: 'Welcome!'});
//If a player disconnects, a message will be sent to all the sockets.
socket.on('disconnect', function(){
game.sockets.emit('exit', {message: 'Player ' + socket.id + ' left the game...!'});
});
//When a player connects, all the players will get this message.
game.sockets.emit('entrance', {message: 'Player ' + socket.id + ' is online'});
});
I want to get a hold of the storePlayers(id)
function. The reason for this being when a socket connects, an object is supposed to be created with the specific socket.id
on the client-side.
How would I go about doing such a thing?
From what I understand, you want the client to send an id
when it connects to your server.You can achieve this by sending a message once the client connects to your server.
Client side
var socket = io.connect('your_server')
socket.on('connect', function () {
clientId = generate_id(); //however you want to generate the id
socket.emit('newUser', {id: clientId});
}
You can then capture the message 'newUser' on the server and retrieve the id of the connected client.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.