2

在 C# 中使用网络流通过TCP序列化自定义对象时,流不可写异常的可能原因是什么。我正在以数据包的形式发送 Mp3 数据。帧由 Byte[] 缓冲区组成。我正在使用二进制格式化程序来序列化对象。

BinaryFormatter.Serialize(NetworkStream,Packet);

在客户端播放的 Mp3 失真和抖动结束了几秒钟,然后引发了上述异常。我正在使用 NAudio 开源库。

在进行此修改之前,我正在使用

NetworkStream.Write(Byte[] Buffer,0,EncodedSizeofMp3); 并且在给出任何异常之前它已经成功写入

4

1 回答 1

3

如果您正在写入 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;
    }
}
于 2012-02-03T16:00:27.167 回答