Search code examples
csockets

socket programming connect() fails the second time I run the loop


Well i am trying to run the server side and the client side in a for loop. The first time I run it, it runs fine but the second time either the connect fails or it gets stuck at accept(). Here's my code:

Client code:

for(i=0;i<2;i++)
{
        if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nError : Connect Failed\n");
        return 1;
    }   

    //***************Writing_I***************
    memset(recvBuff, '0',sizeof(recvBuff));
    ticks = time(NULL);
    snprintf(recvBuff, sizeof(recvBuff), "%.24s\r\n", ctime(&ticks));
    if((n = send(sockfd, recvBuff, strlen(recvBuff), 0))<0)
    {
        printf("Error : send operation failed\n");
    }

    //***************Reading_I***************
    memset(recvBuff, '0', sizeof(recvBuff)); 
    n= recv(sockfd, recvBuff, sizeof(recvBuff)-1, 0);
    {
        printf("bytes read: %d\n", n);
        recvBuff[n] = '\0';
        printf("Data: %s\n",recvBuff);
    } 
    if(n < 0)
    {
        printf("\n Read error \n");
    } 
}
close(sockfd);  

Server code:

if((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL))>=0)
{ 
    for(i=0;i<2;i++)    
    {   
        fd= open("/home/t/Desktop/CS II/A4/test.txt", O_RDONLY);
        //***************Reading***************
        memset(sendBuff, '0', sizeof(sendBuff)); 
        count = recv(connfd, sendBuff, sizeof(sendBuff)-1, 0);
        {
            printf("bytes read: %d\n", count);
            sendBuff[count] = '\0';
            printf("Data: %s\n",sendBuff);
        }
        if(count < 0)
        {
            printf("Read error \n");
        }

        //***************Writing***************
        ticks = time(NULL);
        memset(sendBuff, '0', sizeof(sendBuff)); 
        printf("Reading from file\n");
        if((noOfBytesRd= read(fd, sendBuff, sizeof(sendBuff)-1))<0)
            printf("\n Error : read operation failed\n");
        sendBuff[noOfBytesRd]='\0';
        if((count = send(connfd, sendBuff, strlen(sendBuff), 0))<0)
            printf("\n Error : wtite operation failed\n");
    }
    close(connfd);  
 }

Solution

  • A socket can be connect'ed only once in its life cycle. You should create a separate socket for each connection you intend to make, and close it when you're done with the connection.