websocket++简单使用及实例分析

yizhihongxing

Websocket++简单使用及实例分析

Websocket++是一个C++的WebSocket库,用于实现基于WebSocket协议的网络应用程序。这个库提供了许多的接口和功能,使得程序开发更为简单和高效,同时也支持多种平台和操作系统。本文将详细讲解Websocket++的简单使用及实例分析,帮助读者更好的了解这个库的特点和优势。

Websocket++的简单使用

下面将介绍Websocket++的简单使用步骤和方法:

步骤一:安装Websocket++

在开始之前,你需要先安装Websocket++库。可以通过以下命令在Linux平台中进行安装。

sudo apt-get install libwebsocketpp-dev

步骤二:创建WebSocket服务器

使用Websocket++库创建WebSocket服务器非常简单,只需要按照以下代码编写即可:

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>

using namespace std;

int main() {
    try {
        // 创建服务器
        websocketpp::server<websocketpp::config::asio> server;

        // 设置监听端口和协议
        server.listen(9002);

        // 开始监听请求
        server.start_accept();

        cout << "WebSocket Server started on port 9002" << endl;

        // 进入事件循环
        server.run();
    } catch (websocketpp::exception const & e) {
        cerr << e.what() << endl;
    }
    return 0;
}

上述代码所创建的WebSocket服务器会在本地的9002端口启动,并开始监听请求。执行该程序,可以看到控制台输出 "WebSocket Server started on port 9002",表示WebSocket服务器已经开启。

步骤三:创建WebSocket客户端

使用Websocket++库创建WebSocket客户端同样非常简单,只需要按照以下代码编写即可:

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>

using namespace std;

int main() {
    try {
        // 创建客户端
        websocketpp::client<websocketpp::config::asio_client> client;

        // 设置连接地址
        string uri = "ws://localhost:9002";

        // 连接WebSocket服务器
        client.connect(uri);
        cout << "Connected to " << uri << endl;

        // 进入事件循环
        client.run();
    } catch (websocketpp::exception const & e) {
        cerr << e.what() << endl;
    }
    return 0;
}

上述代码所创建的WebSocket客户端会连接到本地的9002端口,并开始监听服务器发送的数据。执行该程序,可以看到控制台输出 "Connected to ws://localhost:9002",表示WebSocket客户端已经成功连接到服务器。

实例分析

接下来,我们将给出两个Websocket++库的示例,帮助读者更好的了解这个库的使用方法和效果。

示例一:实现在线聊天室

在线聊天室是一个典型的使用WebSocket协议的应用场景,下面我们将使用Websocket++库来实现一个简单的在线聊天室,实现用户之间的实时聊天。

该在线聊天室的具体实现逻辑如下:

  • 用户进入聊天室后,后端记录下该用户的WebSocket连接,同时向所有在线的用户发送该用户进入的提示信息;
  • 用户发送聊天内容后,后端再将该内容发送给所有在线的用户。

下面是详细的实现代码:

服务端实现:

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>
#include <vector>

using namespace std;

typedef websocketpp::server<websocketpp::config::asio> server;

vector<websocketpp::connection_hdl> users;

void on_message(server *sm, websocketpp::connection_hdl hdl, server::message_ptr msg) {
    // 向其他用户广播消息
    for(auto it=users.begin(); it!=users.end(); it++) {
        if (it->lock().get() != hdl.lock().get()) {
            sm->send(*it, msg->get_payload(), msg->get_opcode());
        }
    }
}

void on_open(server *sm, websocketpp::connection_hdl hdl) {
    // 记录新用户,并给其他用户发送进入提示
    users.push_back(hdl);
    for(auto it=users.begin(); it!=users.end(); it++) {
        if (it->lock().get() != hdl.lock().get()) {
            sm->send(*it, "A new user has joined the chat.");
        }
    }
}

void on_close(server *sm, websocketpp::connection_hdl hdl) {
    // 删除离线用户,并通知其他用户
    auto it = find(users.begin(), users.end(), hdl);
    if (it != users.end()) {
        users.erase(it);
    }
    for(auto it=users.begin(); it!=users.end(); it++) {
        sm->send(*it, "A user has left the chat.");
    }
}

int main() {
    try {
        // 创建服务器
        server ws_server;

        // 设置事件处理函数
        ws_server.set_message_handler(bind(&on_message, &ws_server, ::_1, ::_2));
        ws_server.set_open_handler(bind(&on_open, &ws_server, ::_1));
        ws_server.set_close_handler(bind(&on_close, &ws_server, ::_1));

        // 设置监听端口
        ws_server.listen(9002);

        cout << "WebSocket Server started on port 9002" << endl;

        // 进入事件循环
        ws_server.run();
    } catch (const websocketpp::exception& e) {
        cerr << "Error: " << e.what() << endl;
    } catch (...) {
        cerr << "Exception caught" << endl;
    }
    return 0;
}

客户端实现:

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>

using namespace std;

typedef websocketpp::client<websocketpp::config::asio_client> client;

void on_message(client *c, websocketpp::connection_hdl hdl, client::message_ptr msg) {
    cout << msg->get_payload() << endl;
}

int main() {
    try {
        // 创建客户端
        client ws_client;

        // 设置事件处理函数
        ws_client.set_message_handler(bind(&on_message, &ws_client, ::_1, ::_2));

        // 设置连接地址
        string uri = "ws://localhost:9002";

        // 连接WebSocket服务器
        websocketpp::lib::error_code ec;
        client::connection_ptr conn = ws_client.get_connection(uri, ec);
        if (ec) {
            cerr << "Could not connect: " << ec.message() << endl;
            return 1;
        }
        ws_client.connect(conn);

        // 进入事件循环
        ws_client.run();
    } catch (const websocketpp::exception& e) {
        cerr << "Error: " << e.what() << endl;
    } catch (...) {
        cerr << "Exception caught" << endl;
    }
    return 0;
}

启动服务端程序后,运行多个客户端,即可实现在线聊天室的功能。用户在输入聊天内容后,后端会将该内容发送给所有在线用户,实现实时聊天的功能。

示例二:实现Web控制器

Web控制器是一个典型的Websocket应用场景,下面我们将使用Websocket++库来实现一个简单的Web控制器,实现对连接设备的遥控操作。

该Web控制器的具体实现逻辑如下:

  • 用户在Web页面上点击相应的操作按钮后,前端将该操作信息封装为JSON格式并发送给后端;
  • 后端接收到JSON格式的控制信息后,对该设备进行相应的操作并将结果返回给前端。

下面是详细的实现代码:

服务端实现:

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>
#include <string>
#include <json.hpp>

using namespace std;
using json = nlohmann::json;

typedef websocketpp::server<websocketpp::config::asio> server;

// 模拟设备状态
string device_state = "off";

void on_message(server *sm, websocketpp::connection_hdl hdl, server::message_ptr msg) {
    // 解析JSON格式的消息
    json j = json::parse(msg->get_payload());

    // 根据操作类型进行相应的操作
    if (j["type"] == "get_status") {
        json res;
        res["type"] = "status_reply";
        res["state"] = device_state;
        sm->send(hdl, res.dump(), msg->get_opcode());
    } else if (j["type"] == "set_status") {
        device_state = j["state"];
        json res;
        res["type"] = "status_updated";
        res["state"] = device_state;
        for(auto it=sm->get_connections().begin(); it!=sm->get_connections().end(); it++) {
            sm->send(*it, res.dump(), msg->get_opcode());
        }
    }
}

int main() {
    try {
        // 创建服务器
        server ws_server;

        // 设置事件处理函数
        ws_server.set_message_handler(bind(&on_message, &ws_server, ::_1, ::_2));

        // 设置监听端口
        ws_server.listen(9002);

        cout << "WebSocket Server started on port 9002" << endl;

        // 进入事件循环
        ws_server.run();
    } catch (const websocketpp::exception& e) {
        cerr << "Error: " << e.what() << endl;
    } catch (...) {
        cerr << "Exception caught" << endl;
    }
    return 0;
}

客户端实现:

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>
#include <string>
#include <json.hpp>

using namespace std;
using json = nlohmann::json;

typedef websocketpp::client<websocketpp::config::asio_client> client;

void on_message(client *c, websocketpp::connection_hdl hdl, client::message_ptr msg) {
    // 解析JSON格式的消息
    json j = json::parse(msg->get_payload());

    // 根据消息类型进行相应的处理
    if (j["type"] == "status_reply") {
        cout << "Device state: " << j["state"] << endl;
    } else if (j["type"] == "status_updated") {
        cout << "Device state updated: " << j["state"] << endl;
    }
}

int main() {
    try {
        // 创建客户端
        client ws_client;

        // 设置事件处理函数
        ws_client.set_message_handler(bind(&on_message, &ws_client, ::_1, ::_2));

        // 设置连接地址
        string uri = "ws://localhost:9002";

        // 连接WebSocket服务器
        websocketpp::lib::error_code ec;
        client::connection_ptr conn = ws_client.get_connection(uri, ec);
        if (ec) {
            cerr << "Could not connect: " << ec.message() << endl;
            return 1;
        }
        ws_client.connect(conn);

        // 向服务端发送消息
        json msg;
        msg["type"] = "get_status";
        ws_client.send(conn, msg.dump(), websocketpp::frame::opcode::text);

        // 进入事件循环
        ws_client.run();
    } catch (const websocketpp::exception& e) {
        cerr << "Error: " << e.what() << endl;
    } catch (...) {
        cerr << "Exception caught" << endl;
    }
    return 0;
}

启动服务端程序后,运行客户端程序,即可通过该Web控制器对设备进行遥控操作,实现远程控制的功能。

总结

本文介绍了Websocket++库的简单使用方法和两个典型应用场景的实现。 Websocket++库是一个功能强大、易于使用、高效稳定的WebSocket库,具有广泛的应用场景,特别适合于实时通信、远程控制等领域。希望本文能够对读者理解Websocket++库的特点和优势有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:websocket++简单使用及实例分析 - Python技术站

(0)
上一篇 2023年5月28日
下一篇 2023年5月28日

相关文章

  • jsPDF导出pdf示例

    以下是关于如何使用jsPDF导出pdf的详细攻略,包含两个示例。 什么是jsPDF jspdf是一个用于生成PDF文件的JavaScript库。它可以在浏览器端和Node.js环境中使用。它可以轻松地将HTML内容转换为PDF文件,例如HTML文本,SVG图像等。 安装jsPDF 你可以通过npm安装jsPDF: npm install jspdf –sa…

    JavaScript 2023年5月27日
    00
  • js图片加载效果实例代码(延迟加载+瀑布流加载)

    JS图片加载效果是前端开发中非常重要的一环,以提升用户体验为目标,延迟加载和瀑布流加载成为了当前常见的两种图片加载效果。 什么是延迟加载 延迟加载,也叫懒加载,在一个页面中存在很多图片时,没有必要一次性加载所有图片,而是可以只加载第一屏或者可见区域内的图片,当用户向下滚动页面,再异步地去加载剩下的图片。这样可以有效减少页面的加载时间。 实现延迟加载的代码示例…

    JavaScript 2023年6月11日
    00
  • 详解android与HTML混合开发总结

    详解 Android 与 HTML 混合开发总结 介绍 本文主要介绍 Android 和 HTML 混合开发的方法和技巧。Android 和 HTML 的混合开发可以将 Web 和 Native 的优势融合在一起,实现复杂的交互操作,同时保证了应用的性能和稳定性。下面详细介绍如何实现 Android 和 HTML 的混合开发。 WebView 构建基础 We…

    JavaScript 2023年6月11日
    00
  • canvas实现粒子时钟效果

    下面是“canvas实现粒子时钟效果”的完整攻略: 步骤一:设置画布 首先需要在HTML文件中添加一个canvas标签,并设置其宽高。如下面的示例代码所示: <canvas id="canvas" width="600" height="600"></canvas> 接着,在…

    JavaScript 2023年6月11日
    00
  • js实现删除json中指定的元素

    下面是如何实现删除JSON中指定元素的攻略: 1. 找到要删除的元素 在删除JSON中指定元素时,首先要找到要删除的元素。我们可以使用JavaScript的filter()或splice()方法来操作JSON对象。 利用filter()方法: let data = [ {id: 1, name: ‘Alice’}, {id: 2, name: ‘Bob’},…

    JavaScript 2023年5月27日
    00
  • javascript 动态创建表格的2种方法总结

    当我们需要在网页中插入大量的数据时,常常会选择将数据以表格的形式展示出来。使用JS动态创建表格,不仅可以大大减轻前端工作量,还可以根据数据动态生成表格,增加用户体验。 本篇攻略将介绍2种最常见的JS动态创建表格的方法,分别是通过innerHTML方法和DOM API的createElement方法。下面依次介绍这两种方法: 一、innerHTML方法 通过i…

    JavaScript 2023年6月10日
    00
  • asp.net Javascript获取CheckBoxList的value

    下面我将详细讲解如何使用 JavaScript 在 ASP.NET 中获取 CheckBoxList 的值。 1. 获取 CheckBoxList 中选中项的值 要想获取 CheckBoxList 中选中项的值,可以通过以下的方式实现: // 获取 CheckBoxList 的实例 var cbList = document.getElementById(‘…

    JavaScript 2023年6月10日
    00
  • 关于JavaScript与HTML的交互事件

    关于JavaScript与HTML的交互事件的完整攻略,我们可以通过以下步骤进行实现: 1.选中HTML元素 我们可以使用JavaScript选择器去选中我们想要操作的HTML元素,可以是ID、class、标签名等。 示例一: <!DOCTYPE html> <html> <head> <title>选中HTM…

    JavaScript 2023年6月10日
    00
合作推广
合作推广
分享本页
返回顶部