I use NetworkStream
with sockets in an SslStream
socket server as follows:
stream = new NetworkStream(socket, true);
sslStream = new S
If possible, you should use C#'s using
construct to dispose the stream 'automatically' after use:
using (var sslStream = new SslStream(stream, false))
{
// read from stream here...
}
However, if you want to keep the SslStream for later use, you will have to dispose manually.
Disposing a stream typically closes the stream as well, the Close()
method seems to be there mostly for completeness. You can download the .NET source code (or use a decompiler), and examine the SslStream.cs
and its base class AuthenticatedStream.cs
to see the exact behaviour.
To answer the rest of your question - The SslStream is well documented on Microsoft's MSDN site which shows one of SslStream's constructors takes two parameters (also shown by your example). The first parameter is the inner stream - which in your example the NetworkStream
object. The second is a boolean called leaveInnerStreamOpen
. In your example, you pass false
.
It is this second value that determines the behaviour you are asking about: If you pass true
, the inner stream will remain open when you close/dipose the SslStream (the stream will also be flushed). If you pass false
, then the inner stream will be closed too.
Similarly for the NetworkStream
, its constructor also takes a boolean ownsSocket
. If this is set to true
(as in your example), then disposing/closing the NetworkStream will also close its socket, otherwise it stays open.
Therefore, as your example code stands, you must call both sslStream.Dispose()
and stream.Dispose()
(the socket is closed automatically).
However, if you change the second parameter in the SslStream
's constructor to true
in your example code, you can just call sslStream.Dispose()
to close the SslStream
, the NetworkStream
, and its socket.