简介
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

使用
websocketpp,依赖boost库,安装boost

yum install boost
yum install boost-devel
安装websocketpp

地址:https://github.com/zaphoyd/websocketpp

mv websocketpp /usr/include
编写程序websocket.cpp

#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
using namespace std;
typedef websocketpp::server<websocketpp::config::asio> websocketsvr;
typedef websocketsvr::message_ptr message_ptr;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
void OnOpen(websocketsvr *server,websocketpp::connection_hdl hdl){
    cout<<"have client connected"<<endl;
}
void OnClose(websocketsvr *server,websocketpp::connection_hdl hdl){
    cout<<"have client closed"<<endl;
}
void OnMessage(websocketsvr *server,websocketpp::connection_hdl hdl,message_ptr msg){
    server->send(hdl, msg->get_payload(), websocketpp::frame::opcode::text);
}
int main(){
    websocketsvr server;
    server.set_access_channels(websocketpp::log::alevel::all);
    server.clear_access_channels(websocketpp::log::alevel::frame_payload);
    server.init_asio();
    // Register our open handler
    server.set_open_handler(bind(&OnOpen, &server, ::_1));
    // Register our close handler
    server.set_close_handler(bind(&OnClose, &server, _1));
    server.set_message_handler(bind(&OnMessage,&server,_1,_2));
    server.listen(7999);
    server.start_accept();
    server.run();
}

编译程序g++ websocket.cpp -o websocket -lboost_system -std=c++11 -g
websocket在线测试
http://www.websocket-test.com/

参考资料

https://baike.baidu.com/item/WebSocket/1953845