ClientCollection.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package server;
  2. import java.util.ArrayList;
  3. import common.Message;
  4. public class ClientCollection extends ArrayList<Client>{
  5. /**
  6. *
  7. */
  8. private static final long serialVersionUID = 1L;
  9. int maxClients = Server.maxUsers;
  10. public ClientCollection() {
  11. this(Server.maxUsers);
  12. }
  13. public ClientCollection(int maxUsers) {
  14. super(maxUsers);
  15. maxClients = maxUsers;
  16. }
  17. public Client getClientByName(String name) throws NullPointerException {
  18. for (Client c: this) {
  19. if (c.username.equals(name))
  20. return c;
  21. }
  22. return null;
  23. }
  24. void broadcast(Message mess) { //Broadcast to all
  25. if (mess.validate()) {
  26. for (Client c: this)
  27. c.send(mess);
  28. Server.OPClient.send(mess.toString());
  29. }
  30. }
  31. @Override
  32. public boolean add(Client user) throws ArrayIndexOutOfBoundsException { //Add user
  33. if (contains(user))
  34. return true;
  35. if (size() >= maxClients)
  36. throw new ArrayIndexOutOfBoundsException();
  37. else
  38. super.add(user);
  39. return true;
  40. }
  41. public void remove(Client user) { //Remove without DC
  42. remove(user, false);
  43. }
  44. public void remove(Client user, boolean disconnect) { //Remove and disconnect if needed
  45. if (disconnect)
  46. user.disconnect();
  47. super.remove(user);
  48. }
  49. public String listClients() { //String from array
  50. return toString().replace(", ", "\n").replace("[", "").replace("]", "");
  51. }
  52. public String[] listClientsArray() { //Array instead of string
  53. return listClients().split("\n");
  54. }
  55. public void cleanUp() { //Remove unused clients
  56. for (int i = 0; i < size(); i++)
  57. if (!get(i).isConnected())
  58. remove(i);
  59. }
  60. }