在Boost.Asio中同时使用SSL套接字和非SSL套接字?
我正在将一个库转换为Boost.Asio(到目前为止效果很好),但我遇到了一个关于设计决策的绊脚石。
I'm in the process of converting a library to Boost.Asio (which has worked very well so far), but I've hit something of a stumbling block with regards to a design decision.
Boost.Asio提供对SSL的支持,但 boost :: asio :: ssl :: stream< boost :: asio :: ip :: tcp :: socket>
类型必须用于套接字。我的库有连接到SSL服务器或正常连接的选项,所以我已经做了一个类有这样的两个套接字:
Boost.Asio provides support for SSL, but a boost::asio::ssl::stream<boost::asio::ip::tcp::socket>
type must be used for the socket. My library has the option of connecting to SSL servers or connecting normally, so I've made a class with two sockets like this:
class client : public boost::enable_shared_from_this<client>
{
public:
client(boost::asio::io_service & io_service, boost::asio::ssl::context & context) : socket_(io_service), secureSocket_(io_service, context) {}
private:
boost::asio::ip::tcp::socket socket_;
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> secureSocket_;
};
有一堆处理程序引用 socket _
。 (例如,我在几个地方有 socket_.is_open()
,需要成为 secureSocket_.lowest_layer()。is_open() code>为其他套接字。)
And within there are a bunch of handlers that reference socket_
. (For example, I have socket_.is_open()
in several places, which would need to become secureSocket_.lowest_layer().is_open()
for the other socket.)
任何人都可以提出最好的方法去做这个?我不想为此创建一个单独的类,因为这意味着重复很多代码。
Can anyone suggest the best way to go about this? I'd rather not create a separate class just for this purpose, because that would mean duplicating a lot of code.
编辑:我重述了我的原始问题,因为我误解了OpenSSL函数的目的。
I rephrased my original question because I misunderstood the purpose of an OpenSSL function.
有几种方法可以做到这一点。在过去,我做了像
There's a couple of ways you can do this. In the past, I've done something like
if ( sslEnabled )
boost::asio::async_write( secureSocket_ );
} else {
boost::asio::async_write( secureSocket_.lowest_layer() );
}
很多 if / else
语句。您还可以创建一个抽象类(伪代码过简化)
Which can get messy pretty quickly with a lot of if/else
statements. You could also create an abstract class (pseudo code - oversimplified)
class Socket
{
public:
virtual void connect( ... );
virtual void accept( ... );
virtual void async_write( ... );
virtual void async_read( ... );
private:
boost::asio::ip::tcp::socket socket_;
};
然后创建一个派生类 SecureSocket
在 secureSocket _
而不是 socket _
。我不认为它会重复很多代码,并且它可能比 if / else
更清洁每当你需要 async_read
或 async_write
。
Then create a derived class SecureSocket
to operate on a secureSocket_
instead of socket_
. I don't think it would be duplicating a lot of code, and it's probably cleaner than if/else
whenever you need to async_read
or async_write
.