gpt4 book ai didi

c# - NetworkStream 上的 BinaryReader 和 BinaryWriter

转载 作者:行者123 更新时间:2023-11-30 14:22:30 29 4
gpt4 key购买 nike

是否可以通过相同的底层 NetworkStream 同时使用 BinaryReader 和 BinaryWriter

  1. 使用单个线程顺序交错读取和写入?
  2. 使用 1 个线程读取和 1 个线程写入?

(我的目标是通过 TcpClient 连接同时发送和接收数据)

到目前为止,我遇到了两个相关的帖子:

One引用 NetworkStream docs :

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

second引用 BinaryReader docs :

Using the underlying stream while reading or while using the BinaryReader can cause data loss and corruption. For example, the same bytes might be read more than once, bytes might be skipped, or character reading might become unpredictable.

我不是 100% 确定如何解释这些引述,我也不确定我上面的 2 个案例中的哪一个是可能的。

最佳答案

"is"是简短的回答; NetworkStream 本质上充当双工流,读取操作与写入操作完全分开。 BinaryReader 将只使用读取操作,BinaryWriter 将使用写入操作。 LengthPositionSeek 等概念在 NetworkStream 上没有意义,因此不受支持。所以:这里使用BinaryReader/BinaryWriter应该没有冲突。然而,与此同时,我可能会建议反对使用它们 - 仅仅是因为与使用原始 Stream 操作相比,它们实际上通常不会增加太多,并且与任意网络协议(protocol)。如果您正在实现仅使用您的代码的自定义内容:当然,您可能没问题。

有关在使用 BinaryReader/BinaryWriter 时触摸 Stream 的警告仍然非常适用于某些其他流- 例如 FileStream:当读取器/写入器认为它负责时,您可以通过重新定位流来简单地破坏数据 - 因为只有一个位置:这意味着读取会影响写入等. 但是:这根本不适用于NetworkStream。在这方面:NetworkStream 是异常(exception),而不是规则:就您通常对 Stream 的期望而言,NetworkStream 是非常不寻常的。

关于c# - NetworkStream 上的 BinaryReader 和 BinaryWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49251939/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com