简体   繁体   中英

Socket Programming TCP . Server programming looping continuously

Following is the server.c program. When i connect a client to the server, the server starts looping infinitely in receive message part

Server.c

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

int main()
{
    int sid,sid1,bin,lis,n,p,port, pid;
    struct sockaddr_in sin,c;
    socklen_t len;
    char buffer[40]="";
    char buffer1[20]="";
    char ip[30]="192.168.65.241";
    // printf("\nEnter the IP Address :");
    // scanf("%s",ip);
    printf("\nEnter the Port no.:");
    scanf("%d",&port);
    sid=socket(AF_INET,SOCK_STREAM,0);//END POINT CONN,
    if(sid<0)
    {
            perror("Socket : ");
            exit(0);
    }
    printf("\nSocket created successfully...");
    sin.sin_family=AF_INET;
    sin.sin_port=htons(port);
    inet_aton(ip,&sin.sin_addr);//SERVER ADDRESS
    bin=bind(sid,(struct sockaddr*)&sin,sizeof(sin));//BIND ADDRESS WITH SOCKET
    if(bin<0)
    {
            perror("\nBind : ");
            exit(0);
    }
    printf("\nBinding has been done successfully...");
    lis=listen(sid,10);//LISTEN TO THE CLIENT
    if(lis<0)
    {
            perror("\nListen : ");
            exit(0);
    }
    len=sizeof(c);

     while(1){

        printf("A Client is connected to the server.....");
        sid1=accept(sid,(struct sockaddr*)&sin,&len);//ACCEPT CONN.FROM CLIENT
        if(sid1<1)
        {
            perror("\nAccept : ");
            exit(0);
        }
        pid=fork();//CREATE PARENT AND CHILD PROCESS

        if(pid<0){

            perror("ERROR on fork");
            exit(1);
        }
        if(pid==0){

            lis=listen(sid,10);
            printf("\nEnter message...(Type END to terminate):\n");
            scanf("%s",buffer);
            while(strcmp(buffer,"END")!=0)
            {
                send(sid,buffer,30,0);//SEND TO SERVER
                scanf("%s",buffer);
            }
            send(sid,"END",5,0);
            printf("\nTerminating the server...\n");
            exit(0);
        }
        else{

            n=recv(sid,buffer1,30,0);//RECEIVE FROM CLIENT
            buffer[n]='\0';
            n=strcmp(buffer1,"END");
            while(strcmp(buffer1,"END")!=0)
            {
                **printf("\nClient: %s\n",buffer1);** // Infinite Looping
                n=recv(sid,buffer1,30,0);
            }
            printf("\nA client has been disconnected from the server...\n");    
            exit(0);
        }
                            close(sid); //CLOSE CONNECTIONS
                                                                        close(sid1);    //CLOSE CONNECTIONS


     }
    shutdown(sid,2);    //SHUTDOWN READ AND WRITE
    close(sid); //CLOSE CONNECTIONS
}

Client.c

Client program isn't a problem.. Added the code for your reference.

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
int main()
{
    int sid,bi,con,n,p,port;
    char buffer[50],ip[30];
    sid=socket(AF_INET,SOCK_STREAM,0);//END POINT CONN.
    if(sid==-1)
    {
            perror("\nSocket :");
        exit(0);
    }
    printf("A Socket created successfully....");
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    printf("\nEnter the IP Address :");
    scanf("%s",ip);
    printf("\nEnter the Port no. :");
    scanf("%d",&port);
    sin.sin_port = htons(port);
    inet_aton(ip,&sin.sin_addr);
    con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));//CONNECT TO SERVER
    if(con == -1)
    {
        perror("Connection : ");
            exit(0);
    }
    printf("\nConnection is successfull to the server(%s)....\n",ip);
    p=fork();
    if(p)
        {
            printf("\nEnter message...(Type END to terminate):\n");
            scanf("%s",buffer);
            while(strcmp(buffer,"END")!=0)
            {
                    send(sid,buffer,30,0);//SEND TO THE SERVER
                    scanf("%s",buffer);
            }
            send(sid,"END",4,0);
        printf("\nTerminating the client...\n");
        exit(0);
        }
        else
        {
                n=recv(sid,buffer,30,0);//RECV.FROM SERVER
        printf("%d",n);
        buffer[n+1]='\0';
            while(strcmp(buffer,"END")!=0)
            {
                    printf("\nServer: %s\n",buffer);
                    n=recv(sid,buffer,30,0);
            }
            send(sid,"END",4,0);
        exit(0);
        }
    printf("\nClient is terminated...\n");
    shutdown(sid,2);//SHUTDOWN READ AND WRITE
    close(sid); //CLOSE CONNECTIONS
}

Please let me know the Solution ASAP.

The main problem, ie the infinite loop is simply because recv() is being called on the server's main socket ( sid ), not the socket returned by accept() - sid1 . Change this:

n=recv(sid,buffer1,30,0);//RECEIVE FROM CLIENT

to

n=recv(sid1,buffer1,30,0);//RECEIVE FROM CLIENT

and

n=recv(sid,buffer1,30,0);

to

n=recv(sid1,buffer1,30,0);

and you will be in business.

There are other problems with the server code:

  1. recv() is being told to read up to 30 bytes into buffer1 , however, buffer1 is only 20 bytes in size - you have a buffer overrun there.
  2. If the client closes the connection without sending "END" and infinite loop will occur in the receive loop. You need to detect connection closure which is indicated by recv() returning 0.
  3. listen() is being unnecessarily called in the server on line 64.

The above list is probably not exhaustive.

You are using the wrong socket in the calls to read/write in server.c .

Right now, all calls to read/write fail, with errno indicating that the socket isn't connected.

You should use sid1 , the connected socket, instead of sid .

You should also check the return values so you can detect and handle errors.

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