.NET阻塞读取插槽,直至X字节可用?插槽、字节、NET

2023-09-03 05:43:22 作者:傲尊℡

假设我已经实现了TCP,每个消息是由简单的协议:

Assume I have simple protocol implemented over TCP, where each message is made up of:

INT 表示数据的长度。 二进制数据,在1指定的长度。 An int indicating data length. Binary data, of the length specified in 1.

读这样的消息,我想是这样的:

Reading such a message I would like something like:

int length = input.ReadInt();
byte[] data = input.ReadBytes(length);

使用 Socket.Receive NetworkStream.Read 字节可用数量被读取。我想调用的ReadBytes 来阻止,直到长度字节可用。

Using Socket.Receive or NetworkStream.Read the available number of bytes is read. I want the call to ReadBytes to block until length bytes are available.

有没有一种简单的方法来做到这一点,而不必遍历读,重新启动以抵消等待剩余的数据?

Is there a simple way to do this, without having to loop over the read, restarting at an offset waiting for the remaining data?

在实际的应用中读取的可能应该做异步或在后台线程,但我已经忘记了,现在。重要的是要能够有读取才会完成所有数据都可用。

In a real application the read should probably be done Async or on a background thread, but I've ignored that for now. The important thing is to be able to have the read not complete until all data is available.

我知道我可以缓冲数据我自己,我知道该怎么做。这只是一个围绕循环接收的继续在下一个偏移量。如果有一个可重用的实现这样一个循环的,而不需要任何形式的(或者可重复使用的异步实行,当所有数据都可用完成)的自身循环的我所要求的是。

I know that I can buffer the data myself, and I know how to do it. It's just a loop around Receive that continues at the next offset. What I am asking for is if there is a reusable implementation of such a loop, without the need for an own loop of any kind (or alternatively a reusable Async implemenation that finishes when all data is available).

推荐答案

东西,某个地方将不得不进行循环。毕竟,多插槽读取可能是必需的。

Something, somewhere is going to have to loop. After all, multiple socket reads could be required.

我相信 BinaryReader.Read 会不断循环,直到它的多读你问过了,或打流的末尾,但假设你想抛出一个异常,如果到达流的末尾,我会写亲手写单独的方法。这是很容易在一个地方和重用实现,毕竟。

I believe that BinaryReader.Read will keep looping until either it's read as much as you've asked for or hit the end of the stream, but assuming you would want to throw an exception if you reached the end of the stream, I'd write personally write a separate method. It's easy enough to implement in one place and reuse, after all.

 
精彩推荐
图片推荐