C++ WebSocket++使用

参考:https://zhidao.baidu.com/question/1543602972508930467.html
Github下载:git clone https://github.com/zaphoyd/websocketpp.git
WebSocket++的基本使用说明,可以参考《Building a program with WebSocket++》这份文件。
WebSocket++开发说明:
1.要开发程序的时候,基本上要include 两种文件,一种是用来做组态设置(config)的,一种则是用来决定要开发的程序的角色类型(Role)的。
Role:主要分成Server(用来开发服务端) 和Client(用来开发客户端) 两种。
(1) 如果要建立Server 端的程序的话,就是要include Server 用的头文件:
#include <websocketpp/server.hpp>
而之后则是就可以建立出websocketpp::server<>的物件,拿来做操作。
(2) 如果是要建立Client 端程序的话,则是要include Client 的头文件:
#include <websocketpp/client.hpp>
之后则是建立出websocketpp::client<>的物件来做连线。
而WebSocket++的server或client这两种类别,都是template的class,在建立时也需要指定要使用的config才可以。
Config:主要提供了三种类型:config::core(基本上是提供有限功能的设置,相对的他只会用到C++11的功能)、config::asio(是使用Boost ASIO做基础来提供完整的功能)和config::asio_tls(是config::asio再加上TLS的连线加密功能)。
而不同的config也需要include websocketpp/config的目录下不同的头文件:
  core: core.hpp(Server)和core_client.hpp(Client)
  asio: asio_no_tls.hpp(Server)和asio_no_tls_client.hpp(Client)
  asio_tls: asio.hpp(Server)和asio_client.hpp(Client)

最后,如果是要建立使用Boost ASIO、没有TLS 加密的Server 的话,基本要include 的头文件就是:
  #include <websocketpp/server.hpp>
  #include <websocketpp/config/asio_no_tls.hpp>
  而在控制用的物件的部分,则就是:
  websocketpp::server< websocketpp::config::asio > mServer;
  之后,所有的功能就都是针对mServer这个物件进行操作。而在WebSocket++里面,则是把它称为「endpoint」;

服务端:代码示例(摘自Websocketpp示例):
#include < iostream >
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

// pull out the type of messages sent by our config
typedef server::message_ptr message_ptr;
typedef websocketpp::serverwebsocketpp::config::asio server;
using websocketpp::lib::bind;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;

// Define a callback to handle incoming messages
void on_message(server* s, websocketpp::connection_hdl hdl, message_ptr msg)
{
std::cout << "on_message called with hdl: " << hdl.lock().get()
<< " and message: " << msg->get_payload() << std::endl;
// check for a special command to instruct the server to stop listening
// so it can be cleanly exited.
if (msg->get_payload() == “stop-listening”)
{
s->stop_listening();
return;
}
try
{
s->send(hdl, msg->get_payload(), msg->get_opcode());
}
catch (websocketpp::exception const & e)
{
std::cout << "Echo failed because: "<< “(” << e.what() << “)” << std::endl;
}
}
void on_http(server* s, websocketpp::connection_hdl hdl)
{
server::connection_ptr con = s->get_con_from_hdl(hdl);
con->set_body(“Hello World!”);
con->set_status(websocketpp::http::status_code::ok);
}
int main()
{
//Create a server endpoint
server myserver;
try
{
//设置日志级别
myserver.set_access_channels(websocketpp::log::alevel::all);
//屏蔽某个级别的日志
myserver.clear_access_channels(websocketpp::log::alevel::frame_payload);
//调用init_asio()这个函数,初始化内部的Boost ASIO的io_service,作为后续网络连线等功能之使用
myserver.init_asio();
//WebSocket++通过提供各种「Handler」(callback function)做事件的处理;
//设置收到消息时的回调函数
myserver.set_message_handler(bind(&on_message, &myserver, ::_1, ::_2));
myserver.set_http_handler(bind(&on_http, &myserver, ::_1));
//设置关闭连接时的回调函数
myserver.set_close_handler(bind(&on_close, &myserver, ::_1));
//设置打开连接时的回调函数
myserver.set_open_handler(bind(&on_open, &myserver, ::_1));
//调用listen()这个函数,指定要监听的端口
myserver.listen(9002);
//调用start_accept()开始接受输入
myserver.start_accept();
//调用run(),进入 Server的主循环,直到Server 被停下来
myserver.run();
}
catch (websocketpp::exception const & e)
{
std::cout << e.what() << std::endl;
}
catch (…)
{
std::cout << “other exception” << std::endl;
}
}
该示例是通过websocketpp:: server <websocketpp::config:: asio >这个Endpoint,来建立一个使用Boost ASIO、没有TLS加密的WebSocket Server对象myserver。这个程序在执行myserver.run()后,会持续去监听port 9002,当有信息传递进来的时候,就会触发到on_message()这个函数、并把接到的信息进行相应的处理。

那要怎么处理连线进来的信息呢?
WebSocket++是通过提供各种「Handler」(callback function)做事件的处理。
 而这里则是通过set_message_handler(),来设置当Server收到信息时,要执行的callback function,这里就是on_message()这个函数;这也是一般来说,一定会用到的callback function 。
  而message handler 的callback function,会收到两个数据:
  一个是websocketpp::connection_hdl型别的数据,是用来识别目前的连线用的;如果之后要传送信息给client的话,就必须要通过这个物件,来设置要把信息传送给谁。而如果有需要的话,也可以由server<>的get_con_fromhdl()来取得触发这个事件的连线、以及他的资讯。
  第二个则是websocketpp::server<>::message_ptr,里面储存的是传递进来的信息。一般来说,这会通过他的get_payload()函数,来取得传递进来的信息,而得到的数据,会是const string&。不过由于WebSocket也有可能是传递非文字的binary数据,所以可能会需要通过 get_opcode()这个函数,来辨别传递进来的数据的形式。

那如果要送信息给client端要怎么做呢?
基本上就是调用server<>的send()这个函数就可以了。
  s->send(hdl, msg->get_payload(), msg->get_opcode());
  三个参数:
  websocketpp::connection_hdl的物件,让Server知道是要传给哪个client。
  要传递的数据,这边就是直接把收到的信息(msg->get_payload())再传出去;实际上send()有提供不同的介面,实际的数据类型可以是const void*或const string&。
  最后,则是要有一个opcode,来指定要传递的数据的形式;如果是纯文字的话,基本上可以直接指定websocketpp::frame::opcode::TEXT。

客户端:代码示例
#include < iostream >
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
typedef websocketpp::client< websocketpp::config::asio_client > Client;

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

// pull out the type of messages sent by our config
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

void on_message(websocketpp::connection_hdl hdl, message_ptr msg)
{
std::string message = msg->get_payload();

}
int main()
{
//Create a server endpoint
Client myClient;
try
{
//Set logging settings
myClient.clear_access_channels(websocketpp::log::alevel::all);
myClient.set_access_channels(websocketpp::log::alevel::connect);
myClient.set_access_channels(websocketpp::log::alevel::disconnect);
//myClient.set_access_channels(websocketpp::log::alevel::app);
//myClient.set_access_channels(websocketpp::log::alevel::frame_payload);
// 调用init_asio()这个函数,初始化内部的Boost ASIO的io_service,作为后续网络连线等功能之使用
myClient.init_asio();
//WebSocket++通过提供各种「Handler」(callback function)做事件的处理;
myClient.set_message_handler(bind(&on_message, &myClient, ::_1, ::_2));
myClient.set_close_handler(bind(&on_close, &myClient, ::_1));
//设置连接失败时的回调函数
myClient.set_fail_handler(bind(&on_fail, &myClient, ::_1));
myClient.set_open_handler(bind(&on_open, &myClient, ::_1));
std::string m_uri;
websocketpp::lib::error_code ec;
m_con = m_c.get_connection(m_uri, ec);
//m_hdl for function:myClient.send(m_hdl, msg_send, websocketpp::frame::opcode::text)
m_hdl = m_con->get_handle();
myClient.connect(m_con);
//调用run(),
myClient.run();
}
catch (websocketpp::exception const & e)
{
std::cout << e.what() << std::endl;
}
catch (…)
{
std::cout << “other exception” << std::endl;
}
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sky静

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值