refactor ConnectedUsers a bit to make broadcasting easier

This commit is contained in:
Andy Janata 2011-12-24 19:34:57 -08:00
parent c1e033cd65
commit 10a4d4e62e
1 changed files with 43 additions and 10 deletions

View File

@ -1,11 +1,19 @@
package net.socialgamer.cah.data;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import net.socialgamer.cah.data.QueuedMessage.Type;
/**
* Class that holds all users connected to the server, and provides functions to operate on said
* list.
*
* @author ajanata
*
*/
public class ConnectedUsers {
private final Map<String, User> users = new HashMap<String, User>();
@ -15,24 +23,49 @@ public class ConnectedUsers {
}
public void newUser(final User user) {
// TODO fire an event for a new user to interested parties
synchronized (users) {
users.put(user.getNickname(), user);
for (final User u : users.values()) {
final Map<String, Object> data = new HashMap<String, Object>();
data.put("event", "newplayer");
data.put("nickname", user.getNickname());
data.put("timestamp", System.currentTimeMillis());
final QueuedMessage qm = new QueuedMessage(Type.NEW_PLAYER, data);
u.enqueueMessage(qm);
}
final HashMap<String, Object> data = new HashMap<String, Object>();
data.put("event", "new_player");
data.put("nickname", user.getNickname());
broadcastToAll(Type.NEW_PLAYER, data);
}
}
public void removeUser(final User user, final User.DisconnectReason reason) {
// TODO fire an event for a disconnected user to interested parties
synchronized (users) {
// synchronized (users) {
//
// }
}
/**
* Broadcast a message to all connected players.
*
* @param type
* @param masterData
*/
public void broadcastToAll(final Type type, final HashMap<String, Object> masterData) {
broadcastToList(users.values(), type, masterData);
}
/**
* Broadcast a message to a specified subset of connected players.
*
* @param broadcastTo
* @param type
* @param masterData
*/
public void broadcastToList(final Collection<User> broadcastTo, final Type type,
final HashMap<String, Object> masterData) {
synchronized (users) {
for (final User u : broadcastTo) {
@SuppressWarnings("unchecked")
final Map<String, Object> data = (Map<String, Object>) masterData.clone();
data.put("timestamp", System.currentTimeMillis());
final QueuedMessage qm = new QueuedMessage(type, data);
u.enqueueMessage(qm);
}
}
}
}