NetworkStream doesn't support seek operations

前端 未结 4 516
鱼传尺愫
鱼传尺愫 2021-01-24 02:21

I\'m creating simple proxy server but I faced a strange situation, I\'ve following code :

var clientRequestStream = _tcpClient.GetStream();
var requestHeader = c         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-24 02:59

    Are you reading from this stream until the end? If so, I suggest you just copy the entire contents into a MemoryStream, then you can seek on that to your heart's content. In .NET 4 it's particularly easy with Stream.CopyTo:

    MemoryStream dataCopy = new MemoryStream();
    using (var clientRequestStream = _tcpClient.GetStream())
    {
        clientRequestStream.CopyTo(dataCopy);
    }
    dataCopy.Position = 0;
    var requestHeader = dataCopy.GetUtf8String();
    

    It makes sense for NetworkStream not to be seekable - it's just a stream of data that a server is giving to you. Unless you can tell the server to rewind (which only even makes sense in some situations) there's no way of seeking unless something buffers as much data as you need to rewind - which is basically what copying to a MemoryStream does, in a pretty brute-force fashion.

提交回复
热议问题