简体   繁体   English

一次提供多少数据 NetworkStream.Write()?

[英]How much data to feed NetworkStream.Write() at a time?

I'm encrypting data on the fly and writing it to a network stream.我正在动态加密数据并将其写入网络 stream。

Should I write to the stream as soon as each 16-byte encrypted block data becomes available or should I buffer it?我应该在每个 16 字节加密块数据可用时立即写入 stream 还是应该缓冲它? Is there a performance penalty to sending bunches of 16 byte writes rather than a single 20 kilobyte or 1 megabyte write?发送 16 字节的写入而不是单个 20 KB 或 1 兆字节的写入是否会降低性能?

Feed it as much as you have, It will let you know if it can't take any more.尽可能多地喂它,它会让你知道它是否不能再吃。 TCP will handle the buffering for you. TCP 将为您处理缓冲。

Also, the more you feed - the better, it will likely result in less traffic as packets will not be fragmented much.此外,您提供的越多 - 越好,它可能会导致更少的流量,因为数据包不会被分割得太多。

By default Socket uses Nagle algorithm , which is designed to reduce network traffic by causing the socket to buffer small packets and then combine and send them in one packet under certain circumstances.默认情况下,Socket 使用Nagle 算法,该算法旨在通过使套接字缓冲小数据包,然后在某些情况下将它们组合并发送到一个数据包中来减少网络流量。 A TCP packet consists of 40 bytes of header plus the data being sent.一个 TCP 数据包由 40 个字节的 header 加上正在发送的数据组成。 When small packets of data are sent with TCP, the overhead resulting from the TCP header can become a significant part of the network traffic.当使用 TCP 发送小数据包时,由 TCP header 产生的开销可能成为网络流量的重要组成部分。 On heavily loaded networks, the congestion resulting from this overhead can result in lost datagrams and retransmissions, as well as excessive propagation time caused by congestion.在负载较重的网络上,这种开销导致的拥塞会导致数据报丢失和重传,以及拥塞导致的传播时间过长。 The Nagle algorithm inhibits the sending of new TCP segments when new outgoing data arrives from the user if any previously transmitted data on the connection remains unacknowledged.当新的传出数据从用户到达时,如果连接上的任何先前传输的数据仍未得到确认,Nagle 算法将禁止发送新的 TCP 段。

You can turn off Nagle algorithm, but this will likely result in more fragmentation and traffic.您可以关闭 Nagle 算法,但这可能会导致更多的碎片和流量。

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

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