AndroidDev
AndroidDev

Reputation: 21237

Subsequent Messages not Received

I'm working on a networking project. I can successfully send a single message from my client program over to my server program. However, when I send a second message, the server apparently isn't receiving it. I say this because the client program generates output to suggest that the message was sent, but the server shows no reaction at all.

I'm thinking that I am doing something wrong with either select() or FD_ISSET(). Can anyone see what I am doing wrong? Thanks.

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

    int sockfd, newfd;

    struct sockaddr_in clientAddr;
    unsigned int recvLen;
    socklen_t addr_size = sizeof clientAddr;

    fd_set read_set;
    struct timeval tv;

    char buffer[BUFFSIZE];

    // prepare the address struct for the first client
    bzero(&clientAddr,sizeof(clientAddr));                          //zero the struct
    clientAddr.sin_family = AF_INET;                              //address family (ipv4)
    clientAddr.sin_port = htons(SERVER_PORT);  //sets port to network byte order
    clientAddr.sin_addr.s_addr = INADDR_ANY;

    // create a listening connection to listen for requests from clients
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        fprintf(stdout, "Cannot create socket for client 0.\n");
        fprintf(stdout, "Terminating program\n\n");
        exit(1);
    }

    if (bind(sockfd, (struct sockaddr *)&clientAddr, sizeof(clientAddr)) < 0) {
        fprintf (stdout, "Binding failed for client 0\n\n");
        perror("bind failed");
        exit (1);
    }

    if (listen(sockfd, 10) < 0) {
        fprintf (stdout, "Listen() failed\n");
        perror("listen() failed");
        exit (1);
    }

    // accept the connection
    if ((newfd = accept(sockfd, (struct sockaddr *)&clientAddr, &addr_size)) < 0) {
        fprintf(stdout, "Error accepting inbound data from client 0\n");
        perror(" accept() failed");
        exit(EXIT_FAILURE);
    }

    // initialize the fd set
    FD_ZERO(&read_set);
    FD_SET(newfd, &read_set);       // adding our socket to the set
    tv.tv_sec = 0;
    tv.tv_usec = TIMEOUT * 1000;

    while (1) {

        if ( select(newfd+1, &read_set, NULL, NULL, &tv) == -1) {
            perror("select failure");
            fprintf(stdout, "errno: %d\n", errno);
            exit(EXIT_FAILURE);
        }

        if (FD_ISSET(newfd, &read_set)) {
            bzero(buffer, BUFFSIZE);
            recv(newfd, &buffer, BUFFSIZE, 0);

            fprintf(stdout, "Received message: %s\n", buffer);
        }

    }

    return 0;
}

Upvotes: 2

Views: 86

Answers (1)

MeNa
MeNa

Reputation: 1487

After each select you need call FD_ZERO(&read_set); FD_SET(newfd, &read_set); again.

So just move those functions into the loop, before select.

Upvotes: 1

Related Questions