基于websocketpp库的websocket服务器例程

本文详细介绍使用websocketpp库在本地搭建WebSocket服务器的过程,并实现定时向客户端推送数据的功能。通过具体代码示例,展示了如何设置连接回调、消息处理及定时任务,适用于希望深入理解WebSocket服务器开发的读者。

使用websocketpp,需要安装boost。

解压 boost_1_73_0.tar.gz

tar -zvfx boost_1_73_0.tar.gz

运行bootstrap.sh后,生成b2,直接运行b2;如果需要移植到ARM平台,则需要在project-config.jam文件将using gcc修改如下:

using gcc : : arm-linux-gnueabihf-gcc;

生成的库文件在stage目录中。

下面是websocket服务器例程,该服务器功能用于推送数据到客户端,对连接到服务器的客户端,服务器定时推送数据到客户端。这里简单实现了两个推送地址,分别为ws://localhost:9000/push/helloworld和ws://localhost:9000/current/status。

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

#include <set>
#include <string>
#include <iostream>

/*
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>*/
#include <websocketpp/common/thread.hpp>

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

using websocketpp::connection_hdl;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

using websocketpp::lib::thread;
using websocketpp::lib::mutex;
using websocketpp::lib::lock_guard;
using websocketpp::lib::unique_lock;
using websocketpp::lib::condition_variable;

enum action_type {
    SUBSCRIBE,
    UNSUBSCRIBE,
    MESSAGE
};

typedef server::message_ptr message_ptr;

struct action {
    action(action_type t, std::string s, connection_hdl h) : type(t), struri(s), hdl(h) {}
    action(action_type t, std::string s, connection_hdl h, server::message_ptr m)
      : type(t), struri(s), hdl(h), msg(m) {}

    action_type type;
    std::string struri;
    websocket
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值