Game Development Reference
In-Depth Information
On a completed client request, it emits a login event to emit the client:
socket.emit('login');
On a login request from the client, it stores the username in the username session
variable using the socket API function set and emits the loggedIn event to all users
and the emitting client with the username you , as shown in the following code:
socket.on('login', function(username) { socket.set('username',
username, function(err) {
if (err) { throw err; }
var message={};
//message.key="logged";
message.username=username;
socket.broadcast.emit('loggedIn', JSON.stringify(message));
message.username="you";
socket.emit('loggedIn', JSON.stringify(message));
});
});
On the join request, it sets the user session variable, room , with a room name so
that it can be used later. In case the user wants to join another room, we save the
room name to remove the user from the existing room. Hence, we first remove the
user from the existing room and add it to the new room. Then, the code emits the
roomJoined event to all users of the room and the emitting client, as shown in the
following code:
socket.on('join', function(room) { socket.get('room',
function(err, oldRoom) {
if (err) { throw err; }
socket.set('room', room, function(err) {
if (err) { throw err; }
socket.join(room); if (oldRoom) {
socket.leave(oldRoom);
}
socket.get('username', function(err, username) {
if (! username) {
username = socket.id;
}
var message={};
//message.key="join";
message.username=username;
socket.emit('roomJoined', JSON.stringify(message));
socket.broadcast.to(room).emit('roomJoined',
JSON.stringify(message));
});
 
Search WWH ::




Custom Search