正如标题所说,在面向连接的套接字上一次可以写入的字节数是否有限制?
如果我想发送一个缓冲区,例如 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/