可重载的 boost::asio::basic_stream_socket
开发网络应用程序时,我有一个 Connection 类来管理在网络上发送和接收消息。我正在使用 boost::asio。
我现在想让 Connection 类处理通过 TCP 和本地 UNIX 流套接字的连接。然而,boost 的模板设计让我感到困惑。 AFAICT,local::stream_protocol::socket 和 ip::tcp::socket 之间没有共享基类。
我将如何创建一个封装网络语义的连接,以便其他代码不必处理所使用协议的细节?
IE 我想实现类似的东西:
class Connection() {
Connection(ip::tcp::endpoint& ep);
Connection(local::stream_protocol::endpoint& ep);
void send(Buffer& buf);
}
我将如何实现这一点?
Developing a network application, I have a Connection class that manages sending and receiving messages on the network. I'm using boost::asio.
I now want to let the Connection class handle connections both over TCP, and over local UNIX stream sockets. However, the template-design of boost confuses me. AFAICT, there's no shared base-class between local::stream_protocol::socket and ip::tcp::socket.
How would I go about creating a Connection that encapsulates the network-semantics such that other code don't have to deal with the details of what protocol is used?
I.E. I want to implemented something like:
class Connection() {
Connection(ip::tcp::endpoint& ep);
Connection(local::stream_protocol::endpoint& ep);
void send(Buffer& buf);
}
How would I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经过一番思考,我目前的解决方案是将
Connection
的send和recv函数虚拟化,并创建一个Connection
的模板子类,大致是:有没有办法避免是否需要子类化和使用虚函数?
After some pondering, my current solution is to make the send and recv functions of
Connection
virtual, and create a template-subclass ofConnection
, roughly:Is there a way to avoid the need to subclass and use of virtual functions?
所有套接字对象都没有明确地指定基类,文档很好地描述了原理
There is explicitly no base class for all socket objects on purpose, the documentation describes the rationale quite well
请改用 boost::asio:generic::stream_protocol::socket 。当您调用 async_connect()/connect() 时,它将从远程端点提取系列和协议,然后将它们传递给 socket() 系统调用以创建正确的套接字。
还有来自 boost::asio::basic_socket 的代码:
Use boost::asio:generic::stream_protocol::socket instead. When you call async_connect()/connect(), it will extract the family and protocol from the remote endpoint and then pass them to the socket() syscall to create the correct socket.
And there is the code from boost::asio::basic_socket: