在 WebSocket 协议中,分片消息的发送规则如下:

  • 首帧opcode 表示消息的类型(例如,0x02 表示二进制消息),FIN 标志为 0 表示消息尚未结束。

  • 中间帧opcode0x00(表示连续帧),FIN 标志为 0 表示消息尚未结束。

  • 末帧opcode0x00(表示连续帧),FIN 标志为 1 表示消息结束。


typedef websocketpp::client<websocketpp::config::asio_tls_client> Client;
namespace frame {

    bool sendAutoFragmented(
        client_type& client,
        websocketpp::connection_hdl hdl,
        const std::vector<uint8_t>& data,
        size_t maxFrameSize = 1024
    ) {
        // 输入验证
        if (data.empty()) {
            std::cerr << "Error: Empty message cannot be fragmented." << std::endl;
            return false;
        }

        // 确保最大帧大小合理
        if (maxFrameSize < 1) {
            std::cerr << "Error: maxFrameSize must be at least 1 byte." << std::endl;
            return false;
        }

        const size_t totalSize = data.size();
        size_t offset = 0;
    websocketpp::lib::error_code ec;



        using message_type = websocketpp::message_buffer::message<websocketpp::message_buffer::alloc::con_msg_manager>;
        using con_msg_man_type = websocketpp::message_buffer::alloc::con_msg_manager<message_type>;
        auto manager = websocketpp::lib::make_shared<con_msg_man_type>();
        while (offset < totalSize) {
            const size_t remaining = totalSize - offset;
            const size_t currentSize = std::min(maxFrameSize, remaining);
            const bool isLast = (offset + currentSize == totalSize);

            // 创建消息并设置基本属性
            auto msg = manager->get_message(
                websocketpp::frame::opcode::BINARY,
                std::min(currentSize,maxFrameSize)
            );

            msg->set_opcode(offset == 0 ? websocketpp::frame::opcode::BINARY : websocketpp::frame::opcode::continuation);
            msg->set_fin(isLast);

            msg->set_payload(
                reinterpret_cast<const char*>(data.data() + offset),
                currentSize
            );

            client.send(hdl, msg, ec);

            if (ec) {
                std::cerr << "Failed to send fragment "
                          << " (" << currentSize << " bytes): "
                          << ec.message() << std::endl;
                return false;
            }

            offset += currentSize;
        }
        return true;
    }
}  // namespace frame

码共享,共同进步 

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐