IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau C Discussion :

client serveur c++


Sujet :

Réseau C

  1. #1
    Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2013
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Décembre 2013
    Messages : 3
    Points : 3
    Points
    3
    Par défaut client serveur c++
    salut j'ai un petit problème au niveau de serveur il ne veut pas envoyer de message au client lorsqu'il est connecté
    algorithme de serveur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    /********************************************************************
    *   Serveur simple portable (Socket en langage C)
    *             Compilé avec GCC (sous Code::Blocks)
    *
    *        Programed by Bug_Bug: one_piece_555(AT)hotmail.fr
    *
    *   P.S. N'oubliez pas de linker avec la blibiothèque -lws2_32
    *          voir libwsock32.a ou libws2_32.a ou ws2_32.lib ...
    *********************************************************************/
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)  /* Si on compile ce code source sous Windows, alors: */
    #include <winsock2.h>
     
    /**================[ Si Gnu/Linux ]================**/
    #elif defined (linux) /* Sinon si on compile sous linux, alors: */
     
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
     
    #define INVALID_SOCKET -1
    #define SOCKET_ERROR -1
     
    #define closesocket(s) close (s)
    typedef int SOCKET;
    typedef struct sockaddr_in SOCKADDR_IN;
    typedef struct sockaddr SOCKADDR;
     
    /**===============[ Si Autre Systems ]==============**/
    #else
    #error not defined for this platform
    #endif /**========[ Fin teste portabilite' ]========**/
     
    /* Inclure les fichiers d'en-tete dont on a besoin */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    #define DEBUG 0 /** Aclive: 1,  Desactive: 0 **/
    #define SERVER_PORT_LISTENING 3113
     
    int App (void);
    int ConnectWithClient ( SOCKET*, SOCKET* );
    int CommunicatWithClient ( SOCKET );
    int RecvData ( SOCKET socket, char *data );
     
    char buffer[65535];
     
    /**************************************************************************
    * Fonction main():
    * La fonction principale ( le point d'entrer )...
    ***************************************************************************/
    int main (void)
    {
       int flag_main_exit = EXIT_SUCCESS;
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)
       WSADATA wsa_data;
       /* Si l'initialisation sous windows echoue */
       if ( WSAStartup (MAKEWORD (2, 2), &wsa_data) )
          return EXIT_FAILURE;
     
       puts ("Windows: winsock2: OK");
    #endif /**===========[ Fin teste Windows ]==========**/
     
     
       /* si app() retourne 1 c'est qu'elle a echoue' */
       if ( App () )
          flag_main_exit = EXIT_FAILURE;
     
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)
       /* Fermer ce qu'on a initialiser avec WSAStartup */
       WSACleanup ();
    #endif /**===========[ Fin teste Windows ]==========**/
     
       puts("\nPress any key to exit this program ...");
       getchar();
       return flag_main_exit;
    }
     
     
    /**************************************************************************
    * Fonction App():
    ** Le Serveur se connecte avec le client: ConnectToServer()
    ** Si connexion etablie, passer a' la communication CommunicatWithClient()
    ***************************************************************************/
    int App (void)
    {
       SOCKET sock, csock;
       int sock_err;
     
        if( ConnectWithClient (&csock, &sock) )
          return 1; /* retourne 1 s'il y eu probleme */
     
       if ( CommunicatWithClient(csock) )
          return 1; /* retourne 1 s'il y eu probleme */
     
       /* Fin de communication, fermer socket proprement */
       shutdown (sock, 2);   shutdown (csock, 2);
       sock_err = closesocket (sock), sock = INVALID_SOCKET;
       if (sock_err == SOCKET_ERROR)
       {
          perror("Error: sock.closesocket()");
          return 1;
       }
     
       return 0;
    }
     
     
     
    /******************************************************************************
    * Fonction: ConnectWithClient()
    ** Connexion avec le client (avec sock), et recuperation d'infos
    **        sur le client, sur csock ...
    ******************************************************************************/
    int ConnectWithClient ( SOCKET *csock, SOCKET *sock )
    {
       /* Declaration de 2 structures de type SOCKADDR_IN */
       SOCKADDR_IN sin; /* pour le serveur */
       SOCKADDR_IN csin; /* pour le client */
     
       int sock_err, recsize;
     
       FILE* fichier = fopen("log.txt", "a");
     
       /* ouverture du socket */
       if ( (*sock = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
       {
          perror("socket.open");
          return 1; /* Creation du socket a echouer */
       }
     
       printf ("socket %d est maintenant ouvert en mode TCP/IP\n", *sock);
     
       sin.sin_addr.s_addr = htonl (INADDR_ANY); /* Pas besoin d'IP */
       sin.sin_port = htons (SERVER_PORT_LISTENING);  /* port d'ecoute */
       sin.sin_family = AF_INET;  /* famille du protocol (IP) */
     
       /* bind du socket serveur (sock) avec la structure sin du serveur */
       sock_err = bind (*sock, (SOCKADDR *) &sin, sizeof sin);
       if (sock_err == SOCKET_ERROR)
       {
          perror("Error: bind");
          return 1;
       }
     
       /* ecoute sur le port */
       if ( (sock_err = listen (*sock, 5)) == SOCKET_ERROR)
       {
          perror("Error: listen");
          return 1;
       }
       printf ("ecoute sur le port %d...\n", SERVER_PORT_LISTENING);
     
       /* attendre et accepter la connection du client en recuperant les infos
          sur le client dans csin, et en créant le socket du client csock */
       recsize = (int) sizeof csin;
       if( (*csock = accept(*sock, (SOCKADDR*) &csin, &recsize)) == INVALID_SOCKET)
       {
          perror("Error: accept");
          return 1;
       }
       printf ("client connecte avec socket: %d    de: %s   port: %d\n",
                   *csock,    inet_ntoa (csin.sin_addr)    ,htons (csin.sin_port));
     
       if(fichier != NULL)
       {
          fputs("-----------------------------------\n", fichier);
          fprintf(fichier, "client connecte avec socket: %d    de: %s   port: %d\n",
                   *csock,    inet_ntoa (csin.sin_addr)    ,htons (csin.sin_port));
          fputs("-----------------------------------\n", fichier);
     
          fclose(fichier);
       }
     
       return 0;
    }
     
     
     
    /******************************************************************************
    * Fonction: CommunicatWithClient()
    ** Premet d'echanger des donnees avec le Client.   Recevoir ou Envoyer
    ******************************************************************************/
    int CommunicatWithClient ( SOCKET csock )
    {
       char data[500 + 1];
       int sock_err, err_close;
       FILE* fichier = fopen("log.txt", "a");
     
       do
       {
          /* Attendre et recevoire des données envoyé par le client */
          if ( (sock_err = RecvData (csock, data)) == SOCKET_ERROR )
             break;
     
          else
          {
             data[sock_err] = '\0';
     
             printf("> %s\n", data);
     
     
             if(fichier != NULL)
                fprintf(fichier, "> %s\n", data);
          }
       }
       while (1);
     
       if(fichier != NULL)
          fclose(fichier);
     
       /* fermeture du socket client (csock), fin de la communication */
       shutdown (csock, 2);
       err_close = closesocket (csock), csock = INVALID_SOCKET;
       if (err_close == SOCKET_ERROR)
       {
          perror("Error: csock.closesocket()");
          return 1;
       }
     
       return 0;
    }
     
     
     
     
    /******************************************************************************
    * Fonction: RecvData()
    ** Permet de recevoir proprement un Bloc de données
    ** Retourne la taille de data reçu
    ******************************************************************************/
    int RecvData ( SOCKET sock, char *data )
    {
       size_t len_data;
       size_t data_receved = 0;
       char textmode_lendata[25], *pend;
       int n;
     
       /* Recevoir la taille de data */
       n = recv(sock, textmode_lendata, sizeof textmode_lendata - 1, 0);
     
       if (n <= 0)
       {
          if( n == 0 )
             printf("Le Client 'a Quitter...\n");
          return SOCKET_ERROR;
       }
       else
       {
          textmode_lendata[n] = '\0';
          len_data = strtol (textmode_lendata, &pend, 10);
          if (*pend != '\n')
          {
             printf("Invalid data size receved !\n");
             return -1;
          }
       }
     
       /* TantQu'on as pas recu tout, on continue ... */
       while (data_receved < len_data)
       {
          n = recv (sock, data + data_receved, sizeof data - 1, 0);
     
          if (n > 0)
             data_receved += n;
          else
             return SOCKET_ERROR;
       }
     
       return ((int)data_receved);
    }
    algorithme client
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)
    #include <winsock2.h>
     
    /**================[ Si Gnu/Linux ]================**/
    #elif defined (linux)
     
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
     
    #define INVALID_SOCKET -1
    #define SOCKET_ERROR -1
     
    #define closesocket(s) close (s)
    typedef int SOCKET;
    typedef struct sockaddr_in SOCKADDR_IN;
    typedef struct sockaddr SOCKADDR;
     
    /**===============[ Si Autre Systems ]==============**/
    #else
    #error not defined for this platform
    #endif /**========[ Fin teste portabilite' ]========**/
     
    /* Inclure les fichiers d'en-tete dont on a besoin */
    #include <stdio.h>
    #include <stdlib.h>
     
    #define SERVER_PORT_CONNEXION 3113
    char ip_server[15] = "127.0.0.1";  /* localhost */
     
    int App (void);
    int ConnectToServer (SOCKET*);
    int CommunicatWithServer (SOCKET);
    int SendData (SOCKET, char*);
     
     
    /**************************************************************************
    * Fonction main():
    * La fonction principale ( le point d'entrer )...
    ***************************************************************************/
    int main (void)
    {
       int flag_main_exit = EXIT_SUCCESS;
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)
       /* Initialiser WSAStartup() */
       WSADATA wsa_data;
       if ( WSAStartup (MAKEWORD (2, 2), &wsa_data) )
       {
          perror("Error: init WSAStartup()");
          return EXIT_FAILURE;
       }
     
       puts ("WIN: winsock2: OK");
    #endif /**===========[ Fin teste Windows ]==========**/
     
     
       /* si app() retourne 1 c'est qu'elle a echoué */
       if ( App () )
          flag_main_exit = EXIT_FAILURE;
     
    /**==================[ Si Windows ]================**/
    #if defined (WIN32)
       /* Fermer ce qu'on a initialiser avec WSAStartup */
       WSACleanup ();
    #endif /**===========[ Fin teste Windows ]==========**/
     
       puts("\nPress enter this program ...");
       getchar();
       return flag_main_exit;
    }
     
     
    /**************************************************************************
    * Fonction App():
    ** Le Client se connecte au serveur: ConnectToServer()
    ** Si connexion etablie, passer a' la communication CommunicatWithServer()
    ***************************************************************************/
    int App (void)
    {
       SOCKET fdsock;
       int sock_err;
     
       if ( ConnectToServer (&fdsock) )
          return 1; /* retourne 1 s'il y eu probleme */
     
       if ( CommunicatWithServer(fdsock) )
          return 1; /* retourne 1 s'il y eu probleme */
     
       /* Fin de communication, fermer socket proprement */
       shutdown (fdsock, 2);
       sock_err = closesocket (fdsock), fdsock = INVALID_SOCKET;
       if (sock_err == SOCKET_ERROR)
       {
          perror("Error: closesocket()");
          return 1;
       }
     
       return 0; /* Success */
    }
     
     
     
    /******************************************************************************
    * Fonction: ConnectToServer()
    ** Connexion avec le serveur (ip_server) sur le port SERVER_PORT_CONNEXION
    ******************************************************************************/
    int ConnectToServer ( SOCKET* fdSock )
    {
        /* Declaration d'une structure sin de type SOCKADDR_IN
          Qui contiendra les infos consernant le serveur, (IP, port, type) */
       SOCKADDR_IN sin;
     
       /* Creation du socket: */
       if ( (*fdSock = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
       {
          perror("socket.open");
          return 1; /* Creation du socket a echouer */
       }
     
       printf ("socket %d est maintenant ouvert en mode TCP/IP\n", *fdSock);
     
       /* l'IP du serveur avec lequel on va ce connecter: */
       sin.sin_addr.s_addr = inet_addr(ip_server);
       /* le port avec lequel on va ce connecter sur le serveur: */
       sin.sin_port = htons (SERVER_PORT_CONNEXION);
       /* famille du protocol (IP): */
       sin.sin_family = AF_INET;
     
     
       if ( connect(*fdSock, (SOCKADDR *)&sin, sizeof sin) == SOCKET_ERROR )
       {
          perror("Error: connect");
          return 1;
       }
     
       printf ( "Vous etes maintenant connecter au serveur %s sur le port %d\n",
                  ip_server, SERVER_PORT_CONNEXION );
     
       return 0;
    }
     
     
     
     
    /******************************************************************************
    * Fonction: CommunicatWithServer()
    ** Premet d'echanger des donnees avec le Serveur.   Recevoir ou Envoyer
    ******************************************************************************/
    int CommunicatWithServer ( SOCKET fdSock )
    {
       char data[500 + 1], *p = NULL;
       int sock_err, c;
     
       puts("\nVous pouvez saisir votre chaine :\n");
     
       do
       {
          printf("> ");   fflush(stdout);
          fgets (data, sizeof(data), stdin);
          p = strchr(data,'\n');
          if (p == NULL)
             while ((c = fgetc(stdin)) != '\n' && c != EOF);
          else
             *p = '\0';
     
          /* Comande pour quitter */
          if( strcmp(data, "/quit") == 0 )
             break;
     
          /* envoyer data */
          if( (sock_err = SendData (fdSock, data)) == SOCKET_ERROR )
                return 1;
       }
       while (1);
     
       return 0;
    }
     
     
    /******************************************************************************
    * Fonction: SendData()
    ** Permet d'envoyer proprement un Bloc de données. Elle Retourne la taille
       de donnee envoye'
    ******************************************************************************/
    int SendData ( SOCKET socket, char *data )
    {
       int const len_data = strlen (data);
       int data_sent = 0, n;
       char textmode_lendata[25];
     
       sprintf (textmode_lendata, "%d\n", len_data);
     
       /* Envoi de la taille de data, (en mode texte) */
       n = send (socket, textmode_lendata, strlen(textmode_lendata), 0);
     
       if ( n < 0)
       {
          perror("Error: sending data size");
          return SOCKET_ERROR;
       }
     
       /* Envoyer le reste de donnees, s'il en reste */
       while (data_sent < len_data)
       {
          n = send (socket, data + data_sent, len_data - data_sent, 0);
     
          if (n >= 0)
             data_sent += n;
          else
             return SOCKET_ERROR;
       }
     
       return (data_sent);
    }

  2. #2
    Membre émérite
    Avatar de skeud
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2011
    Messages
    1 091
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2011
    Messages : 1 091
    Points : 2 724
    Points
    2 724
    Billets dans le blog
    1
    Par défaut
    Ton message est correct?

    Car si tu attends un retour du serveur et qu'il n'y en a pas, c'est normal:
    Tu ne l'as pas implémenté

    Si c'est le message du client que tu ne reçois pas du serveur, comme ça je vois pas, poste au passage ton log, ç asera utile pour nous aussi.

    PS1: joli code, bien documenté, ça fait plaisir.
    PS2: utilise pas de do----while mais plutot un while tout court, c'est plus jouli et c'est exactement pareil
    Pas de solution, pas de probleme

    Une réponse utile (ou +1) ->
    Une réponse inutile ou pas d'accord -> et expliquer pourquoi
    Une réponse à votre question


  3. #3
    Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Décembre 2013
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Décembre 2013
    Messages : 3
    Points : 3
    Points
    3
    Par défaut je sais mais...
    la probleme j'ai essayer de faire une fonction au niveau serveur d'envoyer un msg mais elle n'a pas fonctionner et je sais pas pk tu peut me donner ou je peut mettre la fonction pour être exécutable

Discussions similaires

  1. Web contre client/serveur que choisir??
    Par silvermoon dans le forum Débats sur le développement - Le Best Of
    Réponses: 41
    Dernier message: 24/01/2004, 15h53
  2. Quel outil pour du développement Client/Serveur (Win XP) ?
    Par jey_bonnet dans le forum Débats sur le développement - Le Best Of
    Réponses: 5
    Dernier message: 02/11/2002, 14h57
  3. Réponses: 2
    Dernier message: 01/10/2002, 12h25
  4. comment gerer plusieurs connexions client/serveur
    Par naili dans le forum C++Builder
    Réponses: 3
    Dernier message: 14/08/2002, 16h58
  5. Langage le mieux adapté pour application client serveur ?
    Par guenus dans le forum Débats sur le développement - Le Best Of
    Réponses: 4
    Dernier message: 17/06/2002, 15h46

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo