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

标签 c sockets tcp buffer byte

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

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

write(tcp_socket, buffer, 1024);

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

最佳答案

write() 不保证所有字节都将被写入,因此需要多次调用 write()。来自 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() 返回写入的字节数,因此必须维护写入字节的运行总数并将其用作 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;
}

关于c - 我一次可以在 TCP 套接字上写入多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15384518/

相关文章:

c - Erlang enif_alloc_resource 总是段错误

c - 如果进程终止但系统继续运行,WriteFile() 会是原子的吗?

c - 程序不工作。编译并运行正常,但如果我输入一个数字,它就会崩溃

C套接字编程通过同一连接发送多个发送和接收

for-loop - 从 go 中的 tcp 连接读取数据是否需要 for 循环?

c - 使用 pthread 和同步

.net - 基于多人回合的 silverlight 游戏的服务器端

linux - 主动关闭服务器套接字

tcp - iptable ubuntu 允许多个特定 ip 到特定端口,放弃其余的吗?

networking - 有没有办法将 ping (icmp) 数据包转换为 TCP 数据包?