0
votes

I want to be able to send or receive an arbitrary amount of data through a socket using the send() and recv() calls. To allow for this, I have created a while loop which does not terminate until the send() or recv() call returns 0 bytes [assuming no error -1]. To account for previously sent or received data:

  1. keep track of the number of bytes returned
  2. continuously call send()/recv() until the functions return 0
  3. update the pointers point at the data so that they only reference data entries that have not yet been processed by send()/recv(). [use pointer arithmetic]

The code that follows is psuedo code written in 'C'
SEND LOOP:

/* bunch of socket code above */
ssize_t condition;
do
{
    ssize_t return_bytes = send(fd_socket, data, DATACHUNK, 0);
    if (return_bytes == -1)
    {
        perror("Problems sending...");
        exit(EXIT_FAILURE);
    }
    condition = return_bytes;
    data = data + return_bytes;
} while (condition > 0);

RECEIVE LOOP:

/* bunch of socket code above */
ssize_t = condition;
ssize_t = total = 0;
memset(data_buffer, 0, BUFFSIZE);
do
{
    ssize_t return_bytes = recv(fd_socket, data_buffer, BUFFSIZE - 1, 0);
    if
    {
        perror("Problems receiving...");
        exit(EXIT_FAILURE);
    }
    condition = return_bytes;
    data_buffer = data_buffer + return_bytes;
    total = total + return_bytes;
} while (condition > 0);
data_buffer[total] = '\0';

Unfortunately, when trying to upgrade a char array[ ] data buffer, I get the error: "array not assignable". I thought arrays decayed to pointer that pointed to the start of the data block in memory (index 0). How can I update the pointer that points at my char array so that I can send a message of arbitrary size? Would it make a difference if I declared character data buffers as:
char * data[DATASIZE] instead of char data[DATASIZE]?

2
An array is not a pointer. You know the index to receive at, use &data_buffer[total] - Retired Ninja

2 Answers

0
votes

Before the loop, create a separate pointer variable that points to the beginning of the array to start. Then pass that pointer to recv to read into and increment the pointer after the call.

0
votes

If you have an array (data_buffer[total]) you can't reassign a new pointer to it (or a different array decaying to a pointer). You can create a pointer pointing into the array though and reassign that as necessary (but it will only be valid as long as the actual array is still on the stack if it was stack-allocated).