client/serveur tcp/ip en c sous unix
Hello, j'ai un debut de client/serveur : le client entre un message, le serveur le recois, en envois un au client et ca s'arrete la, alors que j'aimerais qu'ils puissent coninuer a s'envoyer des messages! Mais je ne sais pas quoi faire pour cela (j'ai essayé en ajoutant une boucle dans le client mais ca ne marche pas...)
voici le code client:
Code:
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
| int sd;
struct sockaddr_in serveur;
//struct hostent *hp;
char buf[256];
sd=socket(AF_INET,SOCK_STREAM,0);
struct hostent *hp = NULL; /* gethostbyname return a structure of this type */
int ret = 0; /* to get the return values */
char hostname[256] = ""; /* Will contain the hostname, returned by gethostname(...)*/
int nb_char = 0; /* Number of char written. Used to get result of sprintf */
/* Initialisation */
sethostent (1); /* Initialisation of host list*/
ret = gethostname (hostname, 256); /* set hostname string */
hp = gethostbyname (hostname); /* fill the 'hp' struct */
serveur.sin_family=AF_INET;
bcopy( (char *)hp->h_addr, (char *)&serveur.sin_addr, hp->h_length);
serveur.sin_port=htons(S_PORT);
connect(sd, (struct sockaddr *)&serveur, sizeof(serveur));
printf("---- enter string : \n");
scanf("%s",buf);
write(sd,buf,sizeof(buf));
read(sd,buf,sizeof(buf));
printf("---- string en retour : %s\n",buf);
}
close(sd);
} |
et le code serveur:
Code:
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
| int sd,nsd,ret; /* socket descriptors */
struct sockaddr_in serveur; /* structure serveur */
struct sockaddr *client; /* structure client */
char buf[256];
int client_size = sizeof(struct sockaddr); /* NOUVEAU */
sd=socket(AF_INET,SOCK_STREAM,0);
if (sd <0) { perror("SOCKET"); exit(1); }
serveur.sin_family=AF_INET;
serveur.sin_addr.s_addr=htons(INADDR_ANY);
serveur.sin_port=htons(S_PORT);
ret=bind(sd,(struct sockaddr *)&serveur,sizeof(serveur));
if (ret <0) { perror("BIND"); exit(1); }
ret=listen(sd,10);
if (ret <0) { perror("LISTEN"); exit(1); }
while (1==1)
{
/*nsd=accept(sd,client,&client_size); /* NOUVEAU ->pour antares?*/
nsd=accept(sd,(struct sockaddr*)&client,&client_size);
if (nsd <0) { perror("ACCEPT"); printf("ERRNO=%d\n", errno); exit(1); }
ret=read(nsd,buf,sizeof(buf));
if (ret <0) { perror("READ"); exit(1); }
printf("%s",buf);
scanf("%s",buf);
//buf[0]='X'; buf[1]='Y'; buf[2]='Z';
ret=write(nsd,buf,sizeof(buf));
if (ret <0) { perror("WRITE"); exit(1); }
close(nsd);
}
close(sd); |
mc!