Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bytes can I write at once on a TCP socket?

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?

like image 593
JustTrying Avatar asked Mar 13 '13 11:03

JustTrying


2 Answers

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;
}
like image 196
hmjd Avatar answered Oct 05 '22 01:10

hmjd


From my experience, it is better to stay in the 1024 byte limit

like image 24
HCLivess Avatar answered Oct 04 '22 23:10

HCLivess