如何识别与 websocketpp 的连接

How to identify a connection with websocketpp

本文关键字:websocketpp 连接 识别 何识别      更新时间:2023-10-16

我有一段使用 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<void>

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

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

编译器抱怨:

错误 C2678:二进制"<":找不到左手的运算符 类型为"const _Ty"的操作数(或没有可接受的转换(

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

你能看到任何其他方法来解决它吗?

有两个问题:

  1. 您使用weak_ptr作为密钥而不使用 std::owner_less。详细信息:如何使用 std::map 和 std::weak_ptr 作为键?
  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(( 方法获取连接的套接字。我从未使用过这种方法,但我认为它应该有效吗?如果您只想存储所有打开的连接及其套接字,则包含连接句柄的 std::vector 可能会更好。