简体   繁体   English

我可以在TCP套接字上一次写入多少字节?

[英]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 如果我想发送一个缓冲区,例如1024字节,我可以使用a

write(tcp_socket, buffer, 1024);

or should I use multiple write() calls with a lower amount of bytes for each one? 或者我应该为每个使用较少字节数的多个write()调用?

write() does not guarantee that all bytes will be written so multiple calls to write() are required. write()不保证将写入所有字节,因此需要多次调用write() 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. 例如,如果底层物理介质上没有足够的空间,或者遇到RLIMIT_FSIZE资源限制(请参阅setrlimit(2)),或者调用被信号处理程序中断,则写入的字节数可能小于count。写得少于计数字节。 (See also pipe(7).) (另见管道(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: write()返回写入的字节数,因此必须保留写入的字节的运行总数,并将其用作buffer的索引并计算要写入的剩余字节数:

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;
}

There's no inherent limit. 没有固有的限制。 TCP/IP will fragment and reassemble packets as required. TCP / IP将根据需要对数据包进行分段和重组。 Your system may impose (a possibly tunable) upper limit, but it is likely to be in the multi-MB range. 您的系统可能会施加(可能是可调的)上限,但它可能在多MB范围内。 See your manpage for setsockopt() and always check write()'s return value. 有关setsockopt()的信息,请参见您的联机帮助页,并始终检查write()的返回值。

The actual amount you can write will depend on the type of socket. 您可以写入的实际数量取决于套接字的类型。 In general, you need to check the return value to see how many bytes were actually written. 通常,您需要检查返回值以查看实际写入的字节数。 The number of bytes written can vary depend on whether the socket is in blocking mode or not. 写入的字节数可以根据套接字是否处于阻塞模式而变化。

Also, if the socket is blocking, you may not want to wait for all the data to be written in one go. 此外,如果套接字阻塞,您可能不想等待所有数据一次写入。 You may want to write some at a time in order to be able to something else in between write operations. 您可能希望一次写一些,以便能够在写操作之间进行其他操作。

根据我的经验,最好保持1024字节的限制

如您所见, 写入套接字的最大缓冲区大小为1048576字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM