How to send a long string in chunks via C sockets without closing the connection?

Viewed 41

There are a couple of things that I'm struggling with here.

The first is how to send a string via C stream sockets when you can't guarantee that the string will be sent/received in one go because it's larger than the BUFSIZs or for some other reason. I imagine that this needs to be done with some sort of infinite loop that you break out of, but I can't figure out how to do this.

The second is I need to do this without breaking the connection. I know that in a lot of implementations infinite loops are broken by the message sender closing the connection, which results in a recv status of 0. The recipient can then use this to break out of their loop. But is there a way of completing the transfer without breaking the connection?

EDIT: As I understand from the comments, I need to do something like the following, but this produces errors:

CLIENT CODE

char message[a_large_number];
snprintf(message, a_large_number, "%s", "a_very_long_string...");
int BUFSIZ = a_small_number;

// establish socket connection

while (1) {
    int sent = send(networkSocket, message, sizeof(message), 0);
    if (sent == (sizeof(message))) {
      break;
    }
  }

// do something else

//close(socket_connection)
SERVER CODE

int BUFSIZ = another_small_number;
char client_message[];

// establish socket connection

while (1) {
  char buffer[BUFSIZ];
  int received = recv(clientSocket, buffer, sizeof(buffer), 0);
  if (received == 0) {
      break;
  }
  strcat(client_message, buffer);
  memset(buffer, 0, sizeof(buffer));
}


// do something else

// close(socket_connection)
0 Answers
Related