client.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * File: client.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 21 novembre 2018
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include "client.h"
  10. /* --- Globale --- */
  11. int id = 0;
  12. ClientList clist;
  13. /* --- Fonctions publiques ---*/
  14. int add_client(Server cli, Server serv){
  15. //Creation client
  16. Client* c = malloc(sizeof(Client));
  17. c->main = server_clone(cli);
  18. c->notify = server_clone(serv);
  19. c->id = id++;
  20. //Creation noeud
  21. ClientNode* cn = malloc(sizeof(ClientNode));
  22. cn->cli = c;
  23. cn->next = NULL;
  24. cn->empty = false;
  25. //Ajout dans la liste
  26. if(clist.length == 0){
  27. clist.tab = cn;
  28. } else {
  29. ClientNode* lastcn = clist.tab;
  30. for(int i = 0; i < clist.length - 1; i++){
  31. lastcn = lastcn->next;
  32. }
  33. lastcn->next = cn;
  34. }
  35. clist.length++;
  36. //Retourne l'id du client
  37. return c->id;
  38. }
  39. Client* get_client(int id){
  40. //Si hors du tableau
  41. if(id >= clist.length){
  42. return NULL;
  43. }
  44. //Recup le noeud
  45. ClientNode* cn = clist.tab;
  46. for(int i = 0; i < id; i++){
  47. cn = cn->next;
  48. }
  49. //Si client suppr
  50. if(cn->empty){
  51. return NULL;
  52. }
  53. return cn->cli;
  54. }
  55. void remove_client(int id){
  56. //Si hors du tableau
  57. if(id >= clist.length){
  58. return;
  59. }
  60. //Recup le noeud
  61. ClientNode* cn = clist.tab;
  62. for(int i = 0; i < id; i++){
  63. cn = cn->next;
  64. }
  65. //Supprime le client
  66. server_close_client(cn->cli->main);
  67. server_close_client(cn->cli->notify);
  68. free(cn->cli->main);
  69. free(cn->cli->notify);
  70. free(cn->cli);
  71. cn->empty = true;
  72. }
  73. void clean_clientlist(){
  74. ClientNode* tmp;
  75. ClientNode* cn = clist.tab;
  76. for(int i = 0; i < clist.length; i++){
  77. if(!cn->empty){
  78. remove_client(i);
  79. }
  80. tmp = cn;
  81. cn = cn->next;
  82. free(tmp);
  83. }
  84. clist.length = 0;
  85. clist.tab = NULL;
  86. }
  87. int get_number_client(){
  88. return clist.length;
  89. }