BinaryReader ReadByte()上是否有超时?

时间:2013-10-16 17:24:15

标签: .net tcp

我继承了一些循环来自BinaryReader的响应的代码,并且它运行正常(返回2个字节)一段时间,但是然后客户端需要一段时间来响应(我假设)并且代码掉落进入捕捉逻辑。

我找不到任何关于ReadByte()等待多长时间的文档,它似乎等待大约3秒钟,然后失败。

有没有人确切知道ReadByte的工作原理?我可以配置它以某种方式等待一段时间吗?我的代码在下面,谢谢。

public virtual Byte[] Send(Byte[] buffer, Int32 recSize) {
    Byte[] rbuffer = new Byte[recSize];

    var binaryWriter = new BinaryWriter(stream);
    var binaryReader = new BinaryReader(stream);

    Int32 index = 0;
    try {
        binaryWriter.Write(buffer);

        do {
            rbuffer[index] = binaryReader.ReadByte(); // Read 1 byte from the stream
            index++;
        } while (index < recSize);

    } catch (Exception ex) {
        Log.Error(ex);
        return rbuffer;
    }
    return rbuffer;
}

PS - 代码中的recSize是2,它总是期望返回2个字节。

1 个答案:

答案 0 :(得分:2)

BinaryReader本身没有超时,它只是底层流的包装器。超时的是你传递给stream的任何流。您必须修改该对象的超时(如果该流只是另一个包装器,则它是父对象。)

您根本不需要使用BinaryReader来做您想做的事情,也假设bufferbyte[]您不需要BinaryWriter。

Byte[] rbuffer = new Byte[recSize];

try {
    stream.Write(buffer, 0, buffer.Length);

    Int32 index = 0;
    do
    {
        index += stream.Read(rbuffer, index, rbuffer.Length - index);
    } while (index < recSize);

} catch (Exception ex) {
    Log.Error(ex);
    return rbuffer; //I would either let the exception bubble up or return null here, that way you can tell the diffrence between a exception and an array full of 0's being read.
}