Patrick
Patrick

Reputation: 1019

Requesting Data on Socket in C

In my C application, I wait for data on the socket in the following way:

printf("Opening socket and wait for data.\n");
while (i < 5)  
   while((connection_fd = accept(socket_fd, 
                            (struct sockaddr *) &address,
                            &address_length)) > -1)
   {
    bzero(buffer, 64);
    n = read(connection_fd,buffer,64);
    if (n < 0) printf("ERROR reading from socket");
    printf("Here is the message of length %d bytes:\n\n", n);
    for (int i = 0; i < n; i++)
    {
      printf("%02X", buffer[i]);
    } 
    printf("\n\n");          
    break;  
    }
 i++
 }

That means I read 5 times data from the Socket, however, by the looks of it I seem to be opening 5 different connections is that right? Is it possible to open the connection just once, keep it alive, and then check whether there is any data available on this connection?

Thanks, Patrick!

Upvotes: 0

Views: 69

Answers (5)

openstk
openstk

Reputation: 137

if (n < 0) printf("ERROR reading from socket");

Why you are going ahead? either break; the loop or continue; for new connection.

Upvotes: 0

iabdalkader
iabdalkader

Reputation: 17312

your code needs some restructuring, you should only accept once for each new connection:

while (1) {
    connection_fd = accept(socket_fd, ...);

    /* check for errors */
    if (connection_fd < 0) {
      /* handle error */
    }

    /* note this could block, if you don't want
       that use non-blocking I/O and select */    
    while ((n=read(connection_fd, buf, ...)) > 0) {
        /* do some work */
    }

    /* close fd */ 
    close(fd);
}

Upvotes: 2

Jay
Jay

Reputation: 24895

It's simple. Move the statement calling accept function outside your loop and then call read using the same socket descriptor.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 59987

Yes. Remove the while (i<5) bit. After the read you can read more data if required.

Upvotes: 0

alk
alk

Reputation: 70883

Sure. To do so you might like to exchange the arguments to the two while() loops:

while ((connection_fd = accept(socket_fd, 
                          (struct sockaddr *) &address,
                          &address_length)) > -1)
  while (i < 5)  
  {
    ...

Upvotes: 0

Related Questions