我可以在 TCP 套接字上一次写入多少字节? [英] How many bytes can I write at once on a TCP socket?

查看:44
本文介绍了我可以在 TCP 套接字上一次写入多少字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,在面向连接的套接字上一次写入的字节数是否有限制?

As the title says, is there a limit to the number of bytes that can be written at once on a connection-oriented socket?

如果我想发送一个缓冲区,例如 1024 字节,我可以使用一个

If I want to send a buffer of, for example, 1024 bytes, can I use a

write(tcp_socket, buffer, 1024);

或者我应该使用多个 write() 调用,每个调用的字节数较少?

or should I use multiple write() calls with a lower amount of bytes for each one?

推荐答案

write() 不保证所有字节都会被写入,所以多次调用 write()是必要的.来自 man write:

write() does not guarantee that all bytes will be written so multiple calls to write() are required. From man write:

写入的字节数可能小于 count,例如,如果底层物理介质空间不足,或者遇到 RLIMIT_FSIZE 资源限制(请参阅 setrlimit(2)),或者在写入少于 count 个字节后调用被信号处理程序中断.(另见管道(7).)

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() 返回写入的字节数,因此必须维护写入的字节总数,并将其用作 buffer 的索引并计算要写入的剩余字节:

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

这篇关于我可以在 TCP 套接字上一次写入多少字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆