C#套接字和SslStreams [英] C# Sockets and SslStreams

查看:52
本文介绍了C#套接字和SslStreams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对处理套接字时使用的最佳"感到困惑.Socket对象提供了Send/Receive方法(和异步等效方法),但也允许创建NetworkStream.使用Socket.Send感到高兴的唯一方法是将调用包装在一个块中,例如:

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();
}

使用SslStream时,如果您在基础套接字上发送消息,那么是否可以通过SSL发送消息?我应该只使用Stream.Write(...)而不是套接字方法吗?

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?

谢谢.

推荐答案

经验法则:

  • 如果您不使用NetworkStream,请使用Socket.Send/Socket.Receive方法.
  • 如果您使用的是NetworkStream(包装Socket),请使用NetworkStream.Read/Write方法,但不要调用Socket方法.
  • 如果要将NetworkStream封装在SslStream中,请在调用AuthenticateAsClient/Server之前使用NetworkStream.Read/Write方法,然后再使用SslStream.Read/Write方法.

在AuthenticateAsClient/Server之后,您的连接将受到SSL保护.那就不要调用Socket或NetworkStream方法:这会破坏SslStream.

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

(在某些情况下可以忽略这些规则,但是您需要非常小心并准确地知道Socket,NetworkStream和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.)

这篇关于C#套接字和SslStreams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆