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

C Discussion :

Socket en C : problème de réception de données


Sujet :

C

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    38
    Détails du profil
    Informations personnelles :
    Âge : 35
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Août 2006
    Messages : 38
    Points : 40
    Points
    40
    Par défaut Socket en C : problème de réception de données
    Bonsoir à tous.

    J'essaye de me créer une bibliothèque TCP/UDP en C pour manipuler des sockets (simplement ^^)

    J'ai un soucis au niveau client. Ceux-ci n'arrivent pas à détecter lorsque des données sont disponibles... (j'utilise la fonction select avec les fdset)

    Voila mon code (c'est encore le chantier pour le moment !)


    server.c
    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
    #include <stdlib.h>
    #include <stdio.h>
    #include "tcp.h"
     
    int main(int argc, char* argv[]) {
    	TcpServer server;
     
    	tcp_init();
     
    	tcp_create_server(&server, 9998);
    	tcp_listen(&server, 99);
    	tcp_kill_server(&server);
     
    	tcp_free();
     
    	return 1;
    }
    client.c
    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
    #include <stdlib.h>
    #include <stdio.h>
    #include "tcp.h"
     
    int main(int argc, char* argv[]) {
    	TcpClient client;
     
    	tcp_init();
     
    	tcp_connect(&client, "127.0.0.1", 9998);
    	//tcp_send(&client, "Bonjour");
     
    	printf("\tWaiting for server message...\n");
    	while(!tcp_has_received_data(&client)) {	// <======= CA BLOQUE ICI !!
     
    	}
     
    	printf("\tNew message from server : ");
    	unsigned int size;
    	char data[1024];
    	tcp_get_data(&client, data, &size);
    	data[size] = '\0';
    	printf("%s\n", data);
     
    	tcp_close(&client);
     
    	tcp_free();
     
    	printf("\n");
    	return 1;
    }
    tch.h
    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
    #ifndef tcp_h
    #define tcp_h
     
    #ifdef WIN32
    	#include <winsock2.h>
    #elif defined (linux)
    	#include <sys/types.h>
    	#include <sys/socket.h>
    	#include <netinet/in.h>
    	#include <arpa/inet.h>
    	#include <unistd.h> /* close */
    	#include <netdb.h> /* gethostbyname */
    	#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;
    	typedef struct in_addr IN_ADDR;
    #else
    	#error not defined for this platform
    #endif
     
    typedef struct TcpClient {
    	SOCKET socket;
    } TcpClient;
     
    typedef struct TcpServer {
    	SOCKET socket;
    	TcpClient ** clients;
    	unsigned int numberOfClients;
    } TcpServer;
     
    int tcp_init();		// done
    void tcp_free();	// done
     
    int tcp_connect(TcpClient * s, char * ip, unsigned int port);	// done
    void tcp_close(TcpClient * s);	// done
     
    int tcp_send(TcpClient * s, void * data);	// done
    int tcp_has_received_data(TcpClient * s);
    int tcp_get_data(TcpClient * s, void * data, unsigned int * size);
     
    int tcp_create_server(TcpServer * s, int port);	// done
    int tcp_listen(TcpServer * s, int maxClients);	// half done
    void tcp_kill_server(TcpServer * s);			// done
     
    void tcp_send_to_all(TcpServer * s, void * data);	// done
     
    #endif
    tcp.c
    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
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <string.h>
    #include "tcp.h"
     
    #define DEBUG 1
     
    /**
     *      Init (for windows only)
     */
    int tcp_init() {
    	if(DEBUG) printf("TCP init ");
    	#ifdef WIN32
    		WSADATA wsa;
    		int err = WSAStartup(MAKEWORD(2, 2), &wsa);
    		if(err < 0)
    		{
    			if(DEBUG) {
    				puts("WSAStartup failed !");
    				exit(EXIT_FAILURE);
    			}
    			return -1;
    		}
    	if(DEBUG) printf(": windows");
    	#endif
    	if(DEBUG) printf("\n");
    	return 1;
    }
     
    /**
     * free (for windows only)
     */
    void tcp_free() {
    	if(DEBUG) printf("TCP free\n");
    	#ifdef WIN32
    	   WSACleanup();
    	#endif
    }
     
    /**
     * connect client to server
     */
    int tcp_connect(TcpClient * s, char * ip, unsigned int port) {
    	SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    	SOCKADDR_IN sin = { 0 };
    	struct hostent *hostinfo;
     
    	if(sock == INVALID_SOCKET)
    	{	
    		if(DEBUG) {
    			perror("socket()");
    			exit(errno);
    		}
    		return -1;
    	}
     
    	hostinfo = gethostbyname(ip);
    	if (hostinfo == NULL)
    	{
    		if(DEBUG) {
    			fprintf (stderr, "Unknown host %s.\n", ip);
    			exit(EXIT_FAILURE);
    		}
    		return -2;
    	}
     
    	sin.sin_addr = *(IN_ADDR *) hostinfo->h_addr;
    	sin.sin_port = htons(port);
    	sin.sin_family = AF_INET;
     
    	if(connect(sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == SOCKET_ERROR)
    	{
    		if(DEBUG) {
    			perror("connect()");
    			exit(errno);
    		}
    		return -3;
    	}
     
    	s->socket = sock;	
     
    	if(DEBUG) printf("* TCP connect : success to connect %s:%d\n", ip, port);
     
    	return 1;
    }
     
    /**
     * close connection to server
     */
    void tcp_close(TcpClient * s) {
    	closesocket(s->socket);
    	if(DEBUG) printf("* TCP close connection\n");
    }
     
    /**
     * send data from client to server
     */
    int tcp_send(TcpClient * s, void * data) {
    	if(send(s->socket, data, strlen(data), 0) < 0)
    	{
    		if(DEBUG) {
    			perror("send()");
    			exit(errno);
    		}
    		return -1;
    	}
    	if(DEBUG) printf("* TCP write data : success\n");
     
    	return 1;
    }
     
    /**
     * return 1 if some data has been received from server
     */
    int tcp_has_received_data(TcpClient * s) {
    	fd_set rdfs;
    	FD_ZERO(&rdfs);
    	FD_SET(s->socket, &rdfs);
     
    	if(DEBUG) printf("\tWait for event\n");
    	if(select(s->socket, &rdfs, NULL, NULL, NULL) == -1)
    	{
    		if(DEBUG) {
    			perror("select()");
    			exit(errno);
    		}
    		return -1;
    	}
    	if(DEBUG) printf("\t Event !\n");
     
    	if(FD_ISSET(s->socket, &rdfs)) {
    		return 1;
    	}
     
    	return 0;
    }
     
    /**
     * return availables data from server
     */
    int tcp_get_data(TcpClient * s, void * data, unsigned int * size) {
    	*size = 0;
     
    	if((*size = recv(s->socket, data, 1024, 0)) < 0)
    	{
    		if(DEBUG) {
    			perror("recv()");
    			exit(errno);
    		}
    		return -1;
    	}
     
    	return 1;
    }
     
     
     
     
     
     
     
     
     
    /**
     * create new tcp server
     */
    int tcp_create_server(TcpServer * s, int port) {
    	SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    	SOCKADDR_IN sin = { 0 };
     
    	if(sock == INVALID_SOCKET)
    	{
    		if(DEBUG) {
    			perror("socket()");
    			exit(errno);
    		}
    		return -1;
    	}	
     
    	s->socket = sock;
    	s->clients = NULL;
    	s->numberOfClients = 0;
     
    	sin.sin_addr.s_addr = htonl(INADDR_ANY);
    	sin.sin_port = htons(port);
    	sin.sin_family = AF_INET;
     
    	if(bind(s->socket,(SOCKADDR *) &sin, sizeof sin) == SOCKET_ERROR)
    	{
    		if(DEBUG) {
    			perror("bind()");
    			exit(errno);
    		}
    		return -2;
    	}
     
    	if(DEBUG) printf("* TCP server create : success (port %d)\n", port);
     
    	return 1;	
    }
     
    // TODO :  THREAD + MUTEX ON TCPSERVER * S !!
    /**
     * wait for client connections
     */
    int tcp_listen(TcpServer * s, int maxClients) {
    	s->clients = (TcpClient **)malloc(maxClients*sizeof(TcpClient*));
     
    	if(listen(s->socket, maxClients) == SOCKET_ERROR)
    	{
    		if(DEBUG) {
    			perror("listen()");
    			exit(errno);
    		}
    		return -1;
    	}
     
    	if(DEBUG) printf("* TCP server listen\n");
     
     
    	while(1) {
    		SOCKADDR_IN csin = { 0 };
    		SOCKET client_socket;
     
    		socklen_t sinsize = sizeof csin;
     
    		client_socket = accept(s->socket, (SOCKADDR *)&csin, &sinsize);
     
    		if(client_socket == INVALID_SOCKET)
    		{
    			if(DEBUG) {
    				perror("accept()");
    				exit(errno);
    			}
    			return -2;
    		}
     
    		s->clients[s->numberOfClients] = (TcpClient *)malloc(sizeof(TcpClient));
    		s->clients[s->numberOfClients]->socket = client_socket;
    		s->numberOfClients++;
     
    		if(DEBUG) tcp_send_to_all(s, "Un nouveau client s'est connecté au serveur !");
    		if(DEBUG) printf("\tNew client (notification send to all)\n");
    	}
     
    	return 1;
    }
     
    /**
     * kill tcp server
     */
    void tcp_kill_server(TcpServer * s) {
    	closesocket(s->socket);
    	if(DEBUG) printf("* TCP kill server\n");
    }
     
    /**
     * send data to all clients
     */
    void tcp_send_to_all(TcpServer * s, void * data) {
    	int i;
     
    	for(i = 0; i < s->numberOfClients; i++) {
    		tcp_send(s->clients[i], data);
    	}
    }
    makefile
    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
    all: client server 
     
    client: client.o tcp.o
    	gcc client.o tcp.o -o client
     
    server: server.o tcp.o
    	gcc server.o tcp.o -o server	
     
    client.o:
    	gcc -Wall client.c -c
     
    server.o: 
    	gcc -Wall server.c -c
     
    tcp.o:
    	gcc -Wall tcp.c -c
     
    clean:
    	rm -f client.o server.o tcp.o client server
     
    rebuild: clean all

    Mon problème se trouve dans client.c
    while(!tcp_has_received_data(&client))

    Normalement tcp_has_received_data devrait me retourner 1 s'il des données sont disponibles... ce qu'il ne fait pas :/

    J'ai lancé un serveur et trois clients et voici ce que j'ai dans la console :
    Pour le serveur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    TCP init 
    * TCP server create : success (port 9998)
    * TCP server listen
    * TCP write data : success
    	New client (notification sent to all)
    * TCP write data : success
    * TCP write data : success
    	New client (notification sent to all)
    * TCP write data : success
    * TCP write data : success
    * TCP write data : success
    	New client (notification sent to all)
    Pour les trois clients
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    TCP init 
    * TCP connect : success to connect 127.0.0.1:9998
    	Waiting for server message...
    	Wait for event
    On voit bien qu'a chaque connexion, le serveur exécute la fonction send_to_all mais que les clients sont toujours en attentent de messages :/:/

    Merci à vous,
    Black Templar

  2. #2
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Août 2011
    Messages
    19
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Août 2011
    Messages : 19
    Points : 33
    Points
    33
    Par défaut
    Hello

    Essaies avec :
    if(select(s->socket+1, &rdfs, NULL, NULL, NULL) == -1)

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    38
    Détails du profil
    Informations personnelles :
    Âge : 35
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Août 2006
    Messages : 38
    Points : 40
    Points
    40
    Par défaut
    Bon, finalement, j'ai trouvé mon erreur !!

    Le select prend en premier paramètre le descripteur de la socket dont la valeur est la plus grande +1...
    J'ai oublié d'ajouter 1 :/

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    if(select(s->socket+1, &rdfs, NULL, NULL, NULL) == -1)
    Comment perdre une demi journée !


    EDIT : Grilled ! Merci mercyril de t'être penché sur la question !

  4. #4
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Août 2011
    Messages
    19
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Août 2011
    Messages : 19
    Points : 33
    Points
    33
    Par défaut
    you're welcome

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Problème de réception de données via QTcpSocket
    Par bilou_2007 dans le forum Débuter
    Réponses: 12
    Dernier message: 16/04/2011, 20h45
  2. Réponses: 3
    Dernier message: 16/09/2010, 20h38
  3. [Indy10][TIdUPDServer] Problème à la réception de données
    Par femtosa dans le forum Web & réseau
    Réponses: 0
    Dernier message: 18/10/2007, 14h28
  4. Réponses: 2
    Dernier message: 06/06/2006, 12h10
  5. Réponses: 5
    Dernier message: 11/03/2004, 15h34

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