C#、java DataInputStream.readFully() 等效项

标签 c# sockets stream windows-store-apps

我正在编写 C# Windows 应用商店应用程序,我通过套接字接收数据。 我想知道,对于 java DataInptStream.ReadFully() 是否有任何 C# 等效方法。 如此处所写http://www.tutorialspoint.com/java/io/datainputstream_readfully.htm

method reads bytes from an input stream and allocates those into the buffer array b.

It blocks until the one of the below conditions occurs: b.length bytes of input data are available. Are there are any equivalent method in C#? That woul wait until length of bytes would de available?

最佳答案

此处缺少 Java 文档中的一些文本,但据我了解,您需要一种方法来准确读取缓冲区较大的字节数,或者失败并抛出某种异常。

BinaryReader.ReadBytes(由 No One 建议)不会像这样:

A byte array containing data read from the underlying stream. This might be less than the number of bytes requested if the end of the stream is reached.

据我所知,没有其他方法具有等效的行为,但您可以使用 extension method 创建它:

public static void ReadFully(this Stream stream, byte[] buffer)
{
    int offset = 0;
    int readBytes;
    do
    {
        // If you are using Socket directly instead of a Stream:
        //readBytes = socket.Receive(buffer, offset, buffer.Length - offset,
        //                           SocketFlags.None);

        readBytes = stream.Read(buffer, offset, buffer.Length - offset);
        offset += readBytes;
    } while (readBytes > 0 && offset < buffer.Length);

    if (offset < buffer.Length)
    {
        throw new EndOfStreamException();
    }
}

然后您可以使用该扩展方法,就好像它是 Stream 类的一部分一样,假设您已经导入了它在以下位置定义的命名空间:

byte[] buffer = new byte[8192];
myNetworkStream.ReadFully(buffer);

关于C#、java DataInputStream.readFully() 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782164/

相关文章:

ajax - jquery $.post() Ajax 是否可以扩展到大规模使用,或者是否保持套接字打开?

c - 使用C在套接字编程中获取请求的地址

python-3.x - 在 python3 中通过套接字发送 .mp4 文件

java - 我必须关闭多少个包装的 Java I/O 对象?

java - 从流中删除开头和结尾字符

c# - 在 Visual Studio 下管理多个目标项目

c# - 在 C# : "...could not find the object..." 中从 Excel 读取错误

Java FileChannel.size() 与 File.length()

c# - 如何保存动态创建的文本框及其值

c# - 如果服务器在从客户端读取所有内容之前发送,为什么我的 C# TcpClient 无法从服务器接收内容?