chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.97k stars 1.22k forks source link

Can tcp::socket and ssl::stream<tcp::socket> use the same set of interfaces? #1548

Open kahotv opened 3 weeks ago

kahotv commented 3 weeks ago

In C#, there is a method like this (pseudo code):

class NetworkStream : Stream { ... }
class SslStream : AuthenticatedStream { ... }
class AuthenticatedStream : Stream { ... }

void Read(Stream local)
{
    byte[] buf = new byte[1024];
    while(true)
    {
        int n = await from.ReadAsync(buf, 0, buf.Length);
        ...
    }

}
//Http:
var stream = new NetworkStream(socket);
//Https:
var stream = new SslStream(new NetworkStream(socket));
//Use:
Trans(stream);

In Asio, I tried this approach, but it requires writing code in the header file. Is there a better way?

template<typename StreamType>
auto Trans(StreamType& local) -> awaitable<void>
{
    char buf[1024];
    while(true)
    {
        size_t n = co_await local.async_read_some(buffer(buf), use_awaitable);
        ...
    }

}

(I'm writing an HTTP and HTTPS proxy program, and I need to use this method.)

Thanks!