在 C# 中使用网络流通过 TCP 序列化自定义对象时,可能会导致流不可写异常。 我以数据包的形式发送 Mp3 数据。帧由 Byte[] 缓冲区组成。我使用二进制格式化程序来序列化对象。
BinaryFormatter.Serialize(NetworkStream,Packet);
Mp3 在客户端播放时出现失真和抖动,结束几秒钟,然后出现上述异常。我正在使用 NAudio 开源库。
在进行此修改之前,我使用的是
NetworkStream.Write(Byte[] Buffer,0,EncodedSizeofMp3); 在给出任何异常之前它已经成功写入
最佳答案
如果您正在写入NetworkStream
,则流/套接字可能会关闭
如果您正在写入 NetworkStream
,它可能是使用 FileAccess.Read
创建的
如果我不得不猜测,但听起来好像有什么东西正在关闭流 - 如果沿途的“作家”假设它拥有该流,则可能会出现这种情况,因此过早地关闭该流。必须编写和使用某种忽略 Close()
请求的包装器 Stream
是很常见的(事实上,我现在面前就有一个,因为我正在编写一些 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;
}
}
关于c# - 流不可写异常的可能原因有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9131394/