I'm Trying find a way to let my server socket open till the connected client send all the messages he wants

52 Views Asked by At

The function CreationFichier I'm trying to make, should create a text document for each message the client send to the server, so that the messages get stocked, and be disposable for the reuse. The thread function mess is the mechanism used to make the client/server sockets communicate between them. Now I'm struggling on finding a way to let my server socket open until the connected client send all the messages he wants, because the client should send 5 messages before it closes it's socket.

void CreationFichier(char * a){
// creating file pointer to work with files
    FILE *fptr;
// opening file in writing mode
    fptr = fopen("tp.txt", "w");
// exiting program 
    if (fptr == NULL) {
        printf("Error!");
        exit(1);
    }
    fprintf(fptr, "%s", a);
    fclose(fptr);;
}
//this is the thread protocol 
void * mess (void * arg){
    int so=*((int *)arg);
    char *mess="Bonjour";
    send(so,mess,strlen(mess)*sizeof(char),0);
    cha buff[100];
    int recu=recv(so,buff,99*sizeof(char),0);
    buff[recu]='\0';
    printf("Recu : %s\n",buff);
    if(strcmp(buff,"PUT")==0){
        CreationFichier(buff);
    }else if(strcmp(buff,"GET")==0){

    }
    free(arg);
    close(so);
}
int main(int argc, char**argv) {
    if(argc!=2){
        printf("Erreur il faut fournir un numero de port");
        return 0;
    }
    int p=atoi(argv[1]);
    int sock=socket(PF_INET,SOCK_STREAM,0);
    struct sockaddr_in adress_sock;
    adress_sock.sin_family=AF_INET;
    adress_sock.sin_port=htons(p);
    adress_sock.sin_addr.s_addr=htonl(INADDR_ANY);
    int r=bind(sock,(struct sockaddr*)&adress_sock,
    sizeof(struct sockaddr_in));
    if(r=0){
        r=listen(sockk,0);
        while(1){
            struct sockaddr_in caller;
            socklen_t size=sizeof(caller); 
            int *sock2=(int *)malloc(sizeof(int));
            *sock2=accept(sock,(struct sockaaddr *)&caller,&size)
            if(*sock2>0){
                printf("Nouvelle connection");
                pthread_t th;
                int r2=pthread_create(&th,NULL,mess,sock2);
                if(r2!=0){
                    printf("Probleme de creation de thread");
                    exit(0);
                }
            }
        }
    }else {
        printf("Probleme de Bind !")
    }
    return 0;
}
0

There are 0 best solutions below