I wrote a simple tcp/ip
connection between a client and a server in localhost in c++
. It sends over tcp/ip an array of unsigned char
. The size of this array is the following:
unsigned char *bytes = (unsigned char*)malloc(sizeof(unsigned char)*96000000);
//array is filled
However when I write on the socket
n = write(sockfd,bytes,96000000);
if(n<0){
cout << "error writing"<< endl;
exit(1);
} else{
cout << "bytes written " << n <<endl;
}
the number of bytes written (the n
variable) that the standard output prints out is 5196978
and not 96000000
as I expected. Why? is there a limit in the number of bytes that I can write in a TCP /IP
connection? How can I solve this problem?
is there a limit in the number of bytes that I can write in a TCP /IP connection? How can I solve this problem?
Yes - your TCP stack (likely part of your Operating System) won't simply let your application enqueue an arbitrary amount of data, potentially taking up absurd amounts of buffer memory outside your app. Instead, it has a limited buffer size and after that's full you're expected to loop around and enqueue more data in the buffer - by further calls to write
- after some has actually been sent over the network. So - loop and resend from where the previous send stopped: if your socket's not been set non-blocking, the call will block until more buffer space is available.