I'm writing a server in c
using WSA that will handle multiple clients. The protocol is something I defined on my own, and the part I'm having trouble with is how to make sure the whole message is actually being sent to the client.
I send
my message once, and than I check how many bytes where actually transferred. Then, if not, I send
again, and as the length of the data that I will now send I use unsentBytes
(see in code).
My problem is that when I try to send the extra bytes that weren't sent, I am currently sending again the entire message. How can I send only the remaining part of the message?
I know I can send only 1 char at a time, and stop recieving on the client side when I get to the end of the message, but I think I can do it like this as well and that it's better.
Is this the right logic to use?
int send_msg(SOCKET s, char *msg, int msg_len)
{
int unsentBytes = msg_len;
int bytesResult = send(s, msg, msg_len, SEND_FLAGS);
unsentBytes -= bytesResult;
while (unsentBytes != 0)
{
bytesResult = send(s, msg, unsentBytes, SEND_FLAGS); // ### msg is the problem
unsentBytes -= bytesResult;
}
}
Here's working code from one of my own projects. Note data + count
to offset into the data.
int sendall(int sd, char *data, int length) {
int count = 0;
while (count < length) {
int n = send(sd, data + count, length, 0);
if (n == -1) {
return -1;
}
count += n;
length -= n;
}
return 0;
}