简体   繁体   中英

Calculate average of numbers in TCP connection

I have to calculate the average of numbers received by a server, then send it to client in a TCP connection in C. The program must be like this: Client sends a message to server with numbers(for example): 2 10 12 --> 2 is number of data and 10 and 12 are the data. Server receives the numbers and sends the count of them to client(in this example count is "2"). It continues until client sends number "0". At this point, server has to send a message to client with number of data calculated and, in the same line, the average of them. If i send "2 10 12" and "2 5 6", server sends to client the message: "4 8.25". "4" is the number of data to calculate and "8.25" is average.

Until now i made the first part for client:

#include <stdio.h>      
#include <sys/types.h>
#include <sys/socket.h>   
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>


int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus= 0;
    char buffsend[256];
    char buffrecv[256];
    char buff[256];
    int i, n, length, ndata;
    float average=0;

    struct sockaddr_in simpleServer;

    if (3 != argc) {

        fprintf(stderr, "Usage: %s <server> <port>\n", argv[0]);
        exit(1);

    }

    /* create a streaming socket      */
    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
        fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for connecting */
    simplePort = atoi(argv[2]);

    /* setup the address structure */
    /* use the IP address sent as an argument for the server address  */
    //bzero(&simpleServer, sizeof(simpleServer)); 
    memset(&simpleServer, '\0', sizeof(simpleServer));
    simpleServer.sin_family = AF_INET;
    //inet_addr(argv[2], &simpleServer.sin_addr.s_addr);
    simpleServer.sin_addr.s_addr=inet_addr(argv[1]);
    simpleServer.sin_port = htons(simplePort);

    /*  connect to the address and port with our socket  */
    returnStatus = connect(simpleSocket, (struct sockaddr *)&simpleServer, sizeof(simpleServer));

    if (returnStatus == 0) {
        fprintf(stderr, "Connect successful!\n");
    }
    else {
        fprintf(stderr, "Could not connect to address!\n");
    close(simpleSocket);
    exit(1);
    }





    /* get the message from the server   */


   do {
        bzero(buffsend, 256);
        printf("insert num dati or terminate(write '0'): ");
        fgets(buffsend,256,stdin);
        n=atoi(buffsend);
        if(n>6) {
          printf("Error\n");

         }
        else {
                length=strlen(buffsend);
                for(i=0;i<n;i++) {
                   printf("insert number: ");
                   length=strlen(buffsend);
                   buffsend[length-1]=' ';
                   fgets(buffsend+length,256-length,stdin); 
                   write(simpleSocket, buffsend, strlen(buffsend)); 
                   read(simpleSocket, buffrecv, 256);
                    }


                 ndata=atoi(buffrecv);
                 printf("DT %d\n", ndata);



             }






      } while((n!=0) && (n>0));



    close(simpleSocket);
    return 0;

}

And this for server:

#include <stdio.h>      
#include <sys/types.h>
#include <sys/socket.h>   
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 



int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus = 0;
    char buff[256];
    char message[256];
    int n, i, DT;
    int count=0;
    float average=0;

    struct sockaddr_in simpleServer;

    if (2 != argc) {

        fprintf(stderr, "Usage: %s <port>\n", argv[0]);
        exit(1);

    }

    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
        fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for listening */
    simplePort = atoi(argv[1]);

    /* setup the address structure */
    /* use INADDR_ANY to bind to all local addresses  */
    memset(&simpleServer, '\0', sizeof(simpleServer)); 
    simpleServer.sin_family = AF_INET;
    simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
    simpleServer.sin_port = htons(simplePort);

    /*  bind to the address and port with our socket  */
    returnStatus = bind(simpleSocket,(struct sockaddr *)&simpleServer,sizeof(simpleServer));

    if (returnStatus == 0) {
        fprintf(stderr, "Bind completed!\n");
    }
    else {
        fprintf(stderr, "Could not bind to address!\n");
    close(simpleSocket);
    exit(1);
    }

    /* lets listen on the socket for connections      */
    returnStatus = listen(simpleSocket, 5);

    if (returnStatus == -1) {
        fprintf(stderr, "Cannot listen on socket!\n");
    close(simpleSocket);
        exit(1);
    }

    while (1)

    {

        struct sockaddr_in clientName = { 0 };
    int simpleChildSocket = 0;
    int clientNameLength = sizeof(clientName);

    /* wait here */

        simpleChildSocket = accept(simpleSocket,(struct sockaddr *)&clientName, &clientNameLength);

    if (simpleChildSocket == -1) {

            fprintf(stderr, "Cannot accept connections!\n");
        close(simpleSocket);
        exit(1);

    }

        /* handle the new connection request  */
    /* write out our message to the client */


        do {
           read(simpleChildSocket, buff, 256);
           num=atoi(buff);
           conta++;
           DT=(conta)-1;
           DT=write(simpleChildSocket, buff, strlen(buff));
           printf("Message received: %s\n", buff);
           bzero(buff, 256); 

     }  while(num!=0);    




     close(simpleChildSocket);
    }

    close(simpleSocket);
    return 0;

}

There are some fixes in your code, especially on the client side. It is more convenient to send a package with |size||data| at once, than each number.

The server side receives the packet, reads the size and accumulates, reads the data and accumulates and then sends size to the client.

If the client sends 0, the server calculates the average and sends the result. I believe it will serve as the initial idea.

cliente side, main loop:

    /*--------cliente side---------*/
    int iResult;/*iResult >1 get from connect*/

    char buffsend[256];
    char szTmp[50]; 
    do {

        menset(buffsend,0,256);/*zero memory*/
        menset(szTmp,0,50);/*zero memory*/
        printf("insert num dati or terminate(write '0'): ");

        fgets(szTmp,50,stdin);
        int n = atoi(szTmp);
        if(n>6) 
            printf("Error\n");
        else 
        { 
            sprintf(buffsend,"%d ",n);
            for(int h=0;h<n;h++)
            {
                printf("insert number: ");
                fgets(szTmp,50,stdin); 
                szTmp[strcspn(szTmp, "\n")] = 0;/*<---remove end line */
                strcat(buffsend,szTmp);/*concatenate new num*/
                strcat(buffsend," ");/*add space*/
            } 
        }
        /*send the data    <len><space><data>  exemp: 2 12 34*/

        iResult = write( ConnectSocket, buffsend, strlen(buffsend) );
        if (iResult == -1) 
        {
            printf("send failed with error: -1\n");
            close(ConnectSocket);
            return 1;
        }
        menset(buffsend,0,256);/*zero memory*/
        iResult = read(ConnectSocket, buffsend, 256);
        if ( iResult > 0 )
            printf("Bytes received: %d  > %s \n", iResult,recvbuf);
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError());

    } while( iResult > 0 );

server side loop:

    /*-------------server side------------*/
    int iResult;/*At this point iResult is greater than 0, by the return of connect*/
    int nNumerator;
    int den;/*Accumulate sizes*/
    float faverage;
    nNumerator=0;
    den = 0;
    faverage=0;

    do 
    {
        memset(recvbuf,0,256);
        iResult = read(ClientSocket, recvbuf, recvbuflen);
        if (iResult > 0) 
        {
            char bufftmp[25];
            int  numpart;
            int  iTmp;
            numpart =0;
            iTmp    =0;
            memset(bufftmp,0,25);
            printf("Bytes received: %d\n", iResult); 
            printf("%s\n",recvbuf);
            /*Traverses all received datar ecvbuf and separates the accumulating size into den, 
            and then accumulates the data in nNumerator*/
            for(int k=0;k<iResult;k++)
            { 
                bufftmp[iTmp++]=recvbuf[k];
                if(recvbuf[k]==' ')
                { 
                    if(!numpart)/*is numpart zero*/
                    {
                        bufftmp[iTmp]='\0';//make space null
                        numpart=atoi(bufftmp);
                        den+=numpart;/*acumalate to average*/
                        printf("lenght: %d\n",numpart);/*get only length*/
                        memset(bufftmp,0,25);
                        if(numpart==0)
                        { 
                            /*go to average*/ 
                            faverage = (float)nNumerator/(float)den;
                        }
                    } 
                    else/* if numparte > 0 get data*/
                    { 
                        bufftmp[iTmp]='\0';  
                        printf("%s ",bufftmp);
                        nNumerator+=atoi(bufftmp);/*save in to buffer of int´s*/ 
                        memset(bufftmp,0,25);
                    }
                    iTmp=0;
                    printf("\n");
                }
            } 
            memset(recvbuf,0,256);
            if(numpart)/*if not zero, send length of data to client*/
                sprintf(recvbuf,"%d",numpart);
            else/*if not, send average*/
                sprintf(recvbuf,"%d %f",den,faverage);

            iResult = write( ClientSocket, recvbuf, strlen(recvbuf));
            if (iResult == -1)
            {
                printf("send failed with error: -1\n");
                close(ClientSocket);
                return 1;
            }

        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  
        {
            printf("recv failed with error: -1\n");
            close(ClientSocket);
            return 1;
        }

    }while (iResult > 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM