0

Could someone tell me a way to send only part of a char array over TCP using write()? I want to send the first 255 bytes and then as another block of data send the next 255 bytes and so on/left over instead of the entire data variable such as:

 n = write(newsockfd,data,strlen(data));

Is there a way to do this?

6
  • Replace strlen(data) with 255? Commented Oct 2, 2013 at 2:06
  • I was thinking about that, i guess i don't understand write() well enough. If i do 255 it will read the first 255 bytes but what if i want to then send the next 255 bytes of the char array after that? I'm trying to send data in blocks instead of one entire thing. Commented Oct 2, 2013 at 2:07
  • 1
    You then need to keep repeating until you have < 255 bytes left. in which case you then send what remains. This will involve keep track of how much of your data buffer has been sent and progress through the buffer accordingly. I guess this is homework? Commented Oct 2, 2013 at 2:10
  • 1
    I found that this book was a good introduction: man7.org/tlpi hope that helps. Commented Oct 2, 2013 at 2:10
  • 1
    So is there some type of pointer/counter that keeps track of where the write left off for some specific data that we are reading from(in this case the data variable). I was under the impression if we repeated the same thing it would just read the same 255 bytes. Commented Oct 2, 2013 at 2:12

1 Answer 1

1
int len = strlen(data);
for (int i = 0; i < len; )
{
    n = write(newsockfd, &data[i], min(len-i, 255));
    if (n < 0) {
        // error, do something ...
        break;
    } 
    i += n;
}

Or:

char *ptr = data;
int len = strlen(data);

while (len > 0)
{
    n = write(newsockfd, ptr, min(len, 255));
    if (n < 0) {
        // error, do something ...
        break;
    } 
    ptr += n
    len -= n;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried the second batch of code and for some reason it breaks very easily. If my file is more than a couple hundred bytes or i am sending too much at once it stalls after i send and nothing gets received on the client side... really baffled.
just tested anything more than 94-95 bytes and it does not send anything to the client anymore. What could cause this?
Do you have the same problem if you use send() instead of write()? Are you sure your client is actually reading and acknowledging the data? Have you looked at the network traffic with a packet sniffer, like Wireshark?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.