tags:

views:

69

answers:

1

I'm confused as to what is "best" to use when dealing with sockets. The Socket object provides Send/Receive methods (and async equivalents), but also allows a NetworkStream to be created. The only way I've had any joy using Socket.Send is by wrapping the call in a block such as:


using (Stream stream = new NetworkStream(socket)) {
  socket.Send(...);
  stream.Flush();
}

When using SslStream, if you send a message on the underlying socket, will it be sent over SSL? Should I just use Stream.Write(...) rather than the socket methods?

Thanks.

+3  A: 

Rules of thumb:

  • If you're not using a NetworkStream, use the Socket.Send/Socket.Receive methods.
  • If you're using a NetworkStream (which is wrapping the Socket), use the NetworkStream.Read/Write methods but don't call the Socket methods.
  • If you're wrapping a NetworkStream in an SslStream, use the NetworkStream.Read/Write methods before calling AuthenticateAsClient/Server, and the SslStream.Read/Write methods after.

After AuthenticateAsClient/Server, your connection will be SSL secured. Don't call the Socket or NetworkStream methods then: this will break the SslStream.

(It's possible to ignore these rules under certain circumstances, but then you need to be really careful and precisely know what Socket, NetworkStream and SslStream do under the hood. If you always use the outermost wrapper, you're on the safe side.)

dtb
Thanks for that. If I then close the SslStream at either end, is it possible to open a new one on the same socket?
QmunkE
@QmunkE: As far as I know, no. Once you created a NetworkStream or SslStream, you use it until the connection closes.
dtb