我一直在引用一个用java编写的开源HTTP代理项目,以便用C#实现我自己的代理;然而,有一些类我在 .Net 中找不到对应的类,例如 InputStream 和 OutputStream。我只是通过从 Stream 类派生来实现我自己的类,但我想知道这是否会使我的系统能够运行。以下是类(class):
public class InputStream:Stream
{
public InputStream(NetworkStream networkStream)
{ }
public InputStream(long Capacity)
{
this.SetLength(Capacity);
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new NotSupportedException("The method or operation is not supported by InputStream");
}
public override long Length
{
get { return this.Length; }
}
public override long Position
{
get
{
return this.Position;
}
set
{
this.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return this.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("The method or operation is not supported by InputStream");
}
}
InputStream 和OutputStream 对象应充当networkStream 对象,只不过InputStream 应仅支持读取操作,而OuputStream 应仅支持写入操作!我想知道这是否是实现两个不同的networkStream对象的好方法,其中一个支持写入,另一个支持读取!
最佳答案
不,您的代码将无法工作。您没有对传递给构造函数的流执行任何操作,并且所有“受支持”的成员只是递归地调用自身,从而导致 StackOverflowException
。
您可以将调用委托(delegate)给您传入的 NetworkStream
,但很难看出这真正会给您带来什么好处。
只需在代理代码中对输入流和输出流使用相同的 NetworkStream
- 您可能不需要编写自己的从 Stream
派生的类.
关于c# - 我的自定义InputStream 和outputStream 对象可以在C# HTTP 程序中工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8354847/