views:

63

answers:

2

Is it possible to use GZipStream passing an SslStream in C#? i.e. can you do


GZipStream stream = new GZipStream(sslStream, CompressionMode.Compress);
stream.Write(...);

...

GZipStream stream = new GZipStream(sslStream, CompressionMode.Decompress);
stream.Read(...);

If this is possible, is the SslStream still in a useable state after this or should it be closed?

Thanks.

A: 

I can't think why not; the SSL stream will just be given bytes, but that is what it expected anyway. The important thing is to close the GZipStream properly, as even Flush() doesn't always really flush (due to having to keep a running buffer for compression). So:

using(GZipStream stream = new GZipStream(sslStream, CompressionMode.Compress)) {
    stream.Write(...);
    stream.Close(); // arguably overkill; the Dispose() from "using" should be enough
}

I'm also assuming that you aren't reading and writing to the same SSL stream (i.e. that is two separate examples, not one example), as that doesn't sound likely to work.

Marc Gravell
Yes, sorry the example was intended to be the client/server sides. If I dispose the GZipStream does it not close my underlying stream? I seemed to be getting ObjectDisposed exceptions when it was wrapped in a using statement...
QmunkE
@qmunke that is optional; see the ctor to gzipstream. It takes a bool iirc.
Marc Gravell
A: 

It is possible and may sometimes work, but it also may sometimes fail. It should work if your protocol always allows you to "cleanly close" the GZipStream before the SSLStream closes. By "cleanly close" I mean that the GZipStream closure effects (the flushing of the compression buffer) can occur and propogate to the peer. It may fail because Ssl allows for rather drastic closure semantics. See section 7.2.1 of RFC 2246.

GregS