How many bytes can I write at once on a TCP socket?
Solution 1
write()
does not guarantee that all bytes will be written so multiple calls to write()
are required. From man write:
The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)
write()
returns the number of bytes written so a running total of the bytes written must be maintained and used as an index into buffer
and to calculate the number of remaining bytes to be written:
ssize_t total_bytes_written = 0;
while (total_bytes_written != 1024)
{
assert(total_bytes_written < 1024);
ssize_t bytes_written = write(tcp_socket,
&buffer[total_bytes_written],
1024 - total_bytes_written);
if (bytes_written == -1)
{
/* Report failure and exit. */
break;
}
total_bytes_written += bytes_written;
}
Solution 2
From my experience, it is better to stay in the 1024 byte limit
Comments
-
JustTrying almost 2 years
As the title says, is there a limit to the number of bytes that can be written at once on a connection-oriented socket?
If I want to send a buffer of, for example, 1024 bytes, can I use a
write(tcp_socket, buffer, 1024);
or should I use multiple
write()
calls with a lower amount of bytes for each one? -
JustTrying about 11 yearsSo I can use any
size
at first, and then I've to check the return values. Is it right? -
Mike about 11 yearsWhy did you put that
assert()
in there? How is it possible to hit that condition? -
hmjd about 11 years@Mike, it is a loop invariant and I like to use them. It might look stupid in this very small snippet but I find them useful. Feel free to take it out.
-
user207421 about 11 yearsNo. Please re-read your source. That's the maximum socket send buffer size, on the IBM z/TPF, whatever that is. It is not the maximum amount of data you can send in a single
send()
orwrite()
, which is only constrained by the maximum value of theint
specifying the length.