如果您正在写入 a NetworkStream
,则流/套接字可能会关闭
如果您正在写入 a NetworkStream
,它可能是用FileAccess.Read
但是,如果我不得不猜测的话,听起来好像有什么东西正在关闭流——例如,如果沿途的“作家”假设它拥有流,那么就会过早地关闭流。必须编写和使用某种Stream
忽略Close()
请求的包装器是很常见的(事实上,我现在有一个包装器,因为我正在编写一些 TCP 代码)。
作为一个小问题;我通常建议不要BinaryFormatter
使用通信(远程处理除外)——最重要的是:它不会以非常友好的方式“版本化”,但在大多数情况下它也往往有点冗长。
这是我目前正在使用的包装器,以防它有帮助(该Reset()
方法欺骗重置位置,因此调用者可以读取相对位置):
class NonClosingNonSeekableStream : Stream
{
public NonClosingNonSeekableStream(Stream tail)
{
if(tail == null) throw new ArgumentNullException("tail");
this.tail = tail;
}
private long position;
private readonly Stream tail;
public override bool CanRead
{
get { return tail.CanRead; }
}
public override bool CanWrite
{
get { return tail.CanWrite; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get { return false; }
}
public override long Position
{
get { return position; }
set { throw new NotSupportedException(); }
}
public override void Flush()
{
tail.Flush();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
int read = tail.Read(buffer, offset, count);
if (read > 0) position += read;
return read;
}
public override void Write(byte[] buffer, int offset, int count)
{
tail.Write(buffer, offset, count);
if (count > 0) position += count;
}
public override int ReadByte()
{
int result = tail.ReadByte();
if (result >= 0) position++;
return result;
}
public override void WriteByte(byte value)
{
tail.WriteByte(value);
position++;
}
public void Reset()
{
position = 0;
}
}