コード例 #1
0
ファイル: controler.c プロジェクト: neokeld/Playground
static void app(void)
{
    SOCKET sock = init_connection();
    char buffer[BUF_SIZE];
    int max = sock;
    /* tableau des clients */
    Client clients[MAX_CLIENTS];

    fd_set rdfs;

    /* Topologie */
    struct graph * graph = initialiser_Graph();

    while(1)
    {
	int i = 0;
	FD_ZERO(&rdfs);

	/* ajouter STDIN_FILENO */
	FD_SET(STDIN_FILENO, &rdfs);

	/* ajouter le socket de connexion */
	FD_SET(sock, &rdfs);

	/* ajouter un socket pour chaque client */
	for(i = 0; i < actual; i++)
	{
	    FD_SET(clients[i].sock, &rdfs);
	}

	if(select(max + 1, &rdfs, NULL, NULL, NULL) == -1)
	{
	    perror("select()");
	    exit(errno);
	}

	/* quelque chose qui rentre depuis le clavier */
	if(FD_ISSET(STDIN_FILENO, &rdfs))
	{
	    /* char message[BUF_SIZE]; */
	    fgets(buffer, BUF_SIZE - 1, stdin);
	    {
		char *p = NULL;
		p = strstr(buffer, "\n");
		if(p != NULL)
		{
		    *p = 0;
		}
		else
		{
		    /* fclean */
		    buffer[BUF_SIZE - 1] = 0;
		}
	    }
	    /* ===Pour écrire à tous les clients===
	       message[0] = 0;
	       strncpy(message, "serveur : ", 0);
	       strncat(message, buffer, 10);
	       for(i = 0; i < actual; i++)
	       {
	       write_client(clients[i].sock, message);
	       } */

	    /* On analyse ce que l'utilisateur tape et on agit en conséquence */
	    if(analyse_cmd(graph, buffer) == 0)
		break; /* L'utilisateur veut quitter */
	}
	else if(FD_ISSET(sock, &rdfs))
	{
	    /* nouveau client */
	    SOCKADDR_IN csin = { 0 };
	    socklen_t sinsize = sizeof(csin);
	    int csock = accept(sock, (SOCKADDR *)&csin, &sinsize);
	    if(csock == SOCKET_ERROR)
	    {
		perror("accept()");
		continue;
	    }

	    /* après s'être connecté le client envoie son nom */
	    if(read_client(csock, buffer) == -1)
	    {
		/* déconnecté */
		continue;
	    }

	    /* quel est le nouveau fd maximum ? */
	    max = csock > max ? csock : max;

	    FD_SET(csock, &rdfs); /* On ajoute le socket à la liste d'écoute */

	    int nbTokens;
	    char **tokens = malloc(MAX_NB_TOKENS*sizeof(char*));
	    nbTokens = strsplit(buffer, tokens, MAX_LEN_LINE, " ");
	    printf("ENVOYE : %s, NB TOKENS : %d\n", buffer, nbTokens);
	    if (nbTokens == 6 && strcmp(tokens[0], "log") == 0 && strcmp(tokens[1], "in") == 0 && strcmp(tokens[2], "as") == 0 && strcmp(tokens[4], "port") == 0)
	    {
		printf("nbTokens == 6\n");
		int port;
		tokens[5][strlen(tokens[5])-1] = '\0';
		port = secure_atoi(tokens[5]);
		/* On cherche si un client utilise déjà le nom demandé
		 * si le nom existe
		 * et si le port est bon*/
		if (port <= 65535 && port >= 0) {
		    printf("port OK\n");
		    int indice_noeud, indice_noeud_gen;
		    Client c;
		    c.sock = csock;
		    c.port_number = port;
		    c.address = inet_ntoa(csin.sin_addr);
		    indice_noeud = exist_Noeud(graph, tokens[3]);
		    indice_noeud_gen = obtenir_Indice_Noeud_Non_Actif(graph);
		    if (indice_noeud < actual  && indice_noeud >= 0 && est_actif_noeud(graph, indice_noeud)== 0) {
			printf("indice noeud OK, %s\n", tokens[3]);
			strcpy(c.name, tokens[3]);
			activer_Noeud(graph, indice_noeud);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			write_client(c.sock, bufG, clients);
		    }
		    else if(indice_noeud_gen != -1) {
			printf("indice noeud gen OK\n");
			strcpy(c.name, obtenir_Nom_Noeud(graph, indice_noeud_gen));
			activer_Noeud(graph, indice_noeud_gen);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			printf("bufG : %s\n", bufG);
			write_client(c.sock, bufG, clients);
			printf("écrit\n");
		    }
		    else {
			printf("Tous les noeuds sont déjà occupés !\n");
		    }

		}
		else
		    printf("Erreur de port : %s\n", tokens[5]);
	    }
	    else if (nbTokens == 4 && strcmp(tokens[0], "log") == 0 && strcmp(tokens[1], "in") == 0 && strcmp(tokens[2], "port") == 0)
	    {
		int port;
		tokens[5][strlen(tokens[5])-1] = '\0';
		port = secure_atoi(tokens[5]);
		/* On cherche si un client utilise déjà le nom demandé
		 * si le nom existe
		 * et si le port est bon*/
		if (port <= 65535 && port >= 0) {
		    int indice_noeud_gen;
		    Client c;
		    c.sock = csock;
		    c.port_number = port;
		    c.address = inet_ntoa(csin.sin_addr);
		    indice_noeud_gen = obtenir_Indice_Noeud_Non_Actif(graph);
		    if(indice_noeud_gen != -1) {
			strcpy(c.name, obtenir_Nom_Noeud(graph, indice_noeud_gen));
			activer_Noeud(graph, indice_noeud_gen);
			clients[actual] = c;
			actual = actual + 1;
			char bufG[BUF_SIZE] = "";
			sprintf(bufG, "greeting %s*\n", c.name);
			/* printf("bufG : %s\n", bufG); */
			write_client(c.sock, bufG, clients);
			/* printf("écrit\n"); */
		    }
		    else {
			printf("Tous les noeuds sont déjà occupés !\n");
		    }
		}
		else
		    printf("Erreur de port : %s\n", tokens[5]);
	    }
	   
	    /*
	    for(i=0; i < nbTokens; i++) {
		free(tokens[i]);
	    }
	    free(tokens);
	    */
	}
	else
	{
	    int i;
	    for(i = 0; i < actual; i++)
	    {
		/* un client parle */
		if(FD_ISSET(clients[i].sock, &rdfs))
		{
		    Client client = clients[i];
		    int c = read_client(clients[i].sock, buffer);
		    /* client déconnecté */
		    if(c == 0)
		    {
			closesocket(clients[i].sock);
			remove_client(clients, i, &actual);
			strncpy(buffer, client.name, BUF_SIZE - 1);
			strncat(buffer, " déconnecté !", BUF_SIZE - strlen(buffer) - 1);
			send_message_to_all_clients(clients, client, actual, buffer, 1);
		    }
		    else
		    {
			/* On analyse la requête du client stockée dans buffer et on lui répond */
			printf("router_poll : %s\n", buffer);
			if(router_poll(graph, &clients[i], buffer, clients) == 0) {
			    /* Si le routeur veut être déconnecté */
			    closesocket(clients[i].sock);
			    remove_client(clients, i, &actual);
			}
			/* ====Pour envoyer un message à tous les routeurs====
			   send_message_to_all_clients(clients, client, actual, buffer, 0); */
		    }
		    break;
		}
	    }
	}
    }

    /* libération des données */
    free_graph(graph);
    clear_clients(clients, actual);
    end_connection(sock);
}
コード例 #2
0
ファイル: server.c プロジェクト: SebHeuze/ProjetReseau2013
/**
* Methode principale
**/
static void app(void)
{

   /* Initialisation du socket */
   SOCKET sock = init_connection();
   char buffer[BUF_SIZE];
   char message[BUF_SIZE];
   /* Index de l'array */
   int actual = 0;
   int max = sock;
   int sizeread;
   /* Le tableau qui va stocker les clients */
   Client clients[MAX_CLIENTS];

   /* Lot de descripteurs */
   fd_set rdfs;

   char *commande;
   char *nomFichier;
   char *contenuFichier;

   while(1)
   {
      int i = 0;
      /* Remise à zéro des descripteurs */
      FD_ZERO(&rdfs);

      /* ajout STDIN_FILENO (console)*/
      FD_SET(STDIN_FILENO, &rdfs);

      /* ajout du socket comme descripteur */
      FD_SET(sock, &rdfs);

      /* Ajout d'un socket pour chaque clients */
      for(i = 0; i < actual; i++)
      {
         FD_SET(clients[i].sock, &rdfs);
      }

      /* Son sélectionne tous les descripteurs prêts */
      if(select(max + 1, &rdfs, NULL, NULL, NULL) == -1)
      {
         perror("select()");
         exit(errno);
      }

      /* SI c'est une entrée clavier */
      if(FD_ISSET(STDIN_FILENO, &rdfs))
      {
         /* Si on a tapé quelque chose au clavier on arrête l'application pour permettre à l'utilisateur d'écrire*/
         break;
      } /* Sinon si c'est une entrée socket  ( nouveau )*/
      else if(FD_ISSET(sock, &rdfs))
      {
         /* Nouveau client */
         SOCKADDR_IN csin = { 0 };
         size_t sinsize = sizeof csin;
         int csock = accept(sock, (SOCKADDR *)&csin, &sinsize);

         if(csock == SOCKET_ERROR)
         {
            perror("accept()");
            continue;
         }

         /* Après s'être connecté le client envoi son pseudo */
        if(read_client(csock, buffer) == -1)
         {
            /* déconnecté */
            continue;
         }

         /* Quel est le nouveau numéro de descripteur max (pour le select) ? */
         max = csock > max ? csock : max;

         /* On ajoute le client à la liste des descripteurs */
         FD_SET(csock, &rdfs);

         /* On ajoute le client à la liste des clients avec son numéro de socket */
         Client c = { csock };
         strncpy(c.name, buffer, BUF_SIZE - 1);
         clients[actual] = c;
         actual++;
      }
      else /* Sinon on vérifie si un client a parlé */
      {
         int i = 0;
         for(i = 0; i < actual; i++) /* Pour chaque client */
         {
            /* On vérifie que le socket du client contient quelque chose */
            if(FD_ISSET(clients[i].sock, &rdfs))
            {
               /* Si c'est le cas on traite le message */
               Client client = clients[i];
               /* On lie le message envoyé par le client */
               int c = read_client(clients[i].sock, buffer);
               /* Client deconnecté */
               if(c == 0)
               {
                  /* Dans ce cas on ferme le socket */
                  closesocket(clients[i].sock);
                  remove_client(clients, i, &actual);
                  strncpy(buffer, client.name, BUF_SIZE - 1);
                  strncat(buffer, " disconnected !", BUF_SIZE - strlen(buffer) - 1);
                  send_message_to_all_clients(clients, client, actual, buffer, 1); /* On notifie tout les clients que ce dernier s'est déconnecté */
               }
               else
               {
                   strcpy(message, buffer);
                   commande = strtok(buffer, " ");
                    if( commande != NULL ) {
                       if(!strncasecmp(commande,"/getfile", strlen(commande))){
                            printf("%s\n", "Début envoi fichier");
                            nomFichier = strtok(NULL, " ");
                            FILE* fp = fopen(nomFichier, "r");
                            sizeread = fread(buffer,sizeof(char),1000,fp);
                            buffer[sizeread] = 0;
                            write(clients[i].sock,buffer,strlen(buffer));
                            printf("%s\n", "Fin envoi fichier");
                       } else if(!strncasecmp(commande,"/sendfile", strlen(commande))){
                            printf("%s\n", "Début réception fichier");
                            nomFichier = strtok(NULL, " ");
                            FILE* fp = fopen(nomFichier, "w");
                            contenuFichier = strtok(NULL, "\0");
                            fprintf(fp,"%s\n",contenuFichier);
                            fclose(fp);
                            printf("%s\n", "Fin réception fichier");
                        } else {

                          /* Sinon on se chargfe juste de relayer le message */
                          send_message_to_all_clients(clients, client, actual, message, 0);
                        }
                     }

               }
               break;
            }
         }
      }
   }

    /* On supprime les clients */
   clear_clients(clients, actual);

   /* On ferme les connexions */
   end_connection(sock);
}