【问题标题】:How to identify a connection with websocketpp如何识别与 websocketpp 的连接
【发布时间】:2019-09-14 01:19:39
【问题描述】:

我有一段代码使用 websocketpp 来运行服务器。我想确定到达服务器的不同连接。为此,似乎应该使用websocketpp::connection_hdl hdl

namespace websocketpp {

/// A handle to uniquely identify a connection.
/**
 * This type uniquely identifies a connection. It is implemented as a weak
 * pointer to the connection in question. This provides uniqueness across
 * multiple endpoints and ensures that IDs never conflict or run out.
 *
 * It is safe to make copies of this handle, store those copies in containers,
 * and use them from other threads.
 *
 * This handle can be upgraded to a full shared_ptr using
 * `endpoint::get_con_from_hdl()` from within a handler fired by the connection
 * that owns the handler.
 */
typedef lib::weak_ptr<void> connection_hdl;

但正如你所见,这是一个weak_ptr&lt;void&gt;,我不知道如何与其他人进行比较。

我有一张以websocketpp::connection_hdl 作为索引的地图,当我尝试查看是否存在以下索引时:

std::map<websocketpp::connection_hdl, asio::ip::tcp::socket> active_connections;
if (active_connections.count(con->get_socket()) > 0) {}

编译器抱怨:

错误 C2678:二进制“

有什么方法可以从连接中获取套接字(原始整数套接字)。如果可以,我可以将其用作索引并解决问题。

你能找到其他解决方法吗?

【问题讨论】:

    标签: c++ websocket


    【解决方案1】:

    有两个问题:

    1. 您正在使用weak_ptr 作为键,而没有使用std::owner_less。更多信息:How can I use a std::map with std::weak_ptr as key?
    2. 在您的示例中,您使用套接字作为键而不是 connection_hdl。

    解决方案:

    std::map<websocketpp::connection_hdl, boost::asio::ip::tcp::socket, std::owner_less<websocketpp::connection_hdl>> active_connections;
    if (active_connections.count(con) > 0) {}
    

    然而,映射没有多大意义:如果你有connection_hdl,你可以用get_socket() 方法获取连接的socket。我从未使用过这种方法,但我认为它应该有效?如果您只想存储所有打开的连接及其套接字,则包含连接句柄的 std::vector 可能会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多