开发者

C# Sockets and SslStreams

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 s开发者_如何学Pythontream = 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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜