Using SslStream with IOCP

2020-04-19 06:36发布

问题:

I have written a TCP server using the Socket class's asynchronous/IOCP methods, BeginSend()/BeginRead()/etc. I would like to add SSL capability using SslStream, but from the interface it looks like Socket and SslStream are not intended to work together, in particular because I'm not using Streams at all and SslStream appears to depend on having a Stream to work with.

Is this possible, or am I looking in the wrong place? Do I need to fashion my own Stream subclass that feeds into my Socket instances and point SslStream at that? It's important to me that my server use IOCP due to scaling concerns.

回答1:

Wrap your Socket in a NetworkStream to use it with an SslStream.

Socket socket;
...
using (var networkStream = new NetworkStream(socket, true))
using (var sslStream = new SslStream(networkStream, ...))
{
   // use sslStream.BeginRead/BeginWrite here
}

Streams expose BeginRead/BeginWrite methods as well, so you don't loose this aspect.