前言
html5支持使用websocket协议与服务器保持一个长连接,方便双方互相传输数据,而且服务器也能主动发送信息给客户端,而在这之前使用HTTP是很难做到的。下面介绍使用C++实现的websocket++的简单使用。websocket++更详细介绍点此。
websocket++需要boost的支持,所以工程中需要包含boost的头文件和库。boost在VS中的如何使用参考此文章。
C++代码
#include "stdafx.h" #include <iostream> using namespace std; #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> typedef websocketpp::server<websocketpp::config::asio> WebsocketServer; typedef WebsocketServer::message_ptr message_ptr; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; void OnOpen(WebsocketServer *server, websocketpp::connection_hdl hdl) { cout << "have client connected" << endl; } void OnClose(WebsocketServer *server, websocketpp::connection_hdl hdl) { cout << "have client disconnected" << endl; } void OnMessage(WebsocketServer *server, websocketpp::connection_hdl hdl, message_ptr msg) { string strMsg = msg->get_payload(); cout << strMsg << endl; string strRespon = "receive: "; strRespon.append(strMsg); server->send(hdl, strRespon, websocketpp::frame::opcode::text); } int main() { WebsocketServer server; // Set logging settings server.set_access_channels(websocketpp::log::alevel::all); server.clear_access_channels(websocketpp::log::alevel::frame_payload); // Initialize ASIO 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)); // Register our message handler server.set_message_handler(bind(&OnMessage, &server, _1, _2)); //Listen on port 2152 server.listen(8090); //Start the server accept loop server.start_accept(); //Start the ASIO io_service run loop server.run(); return 0; }
Html代码
<!DOCTYPE html> <html> <head> <title>Testing websockets</title> </head> <body> <div> <input type="submit" value="Start" onclick="start()" /> </div> <div id="messages"></div> <script type="text/javascript"> var webSocket = new WebSocket('ws://localhost:8090'); webSocket.onerror = function(event) { onError(event) }; webSocket.onopen = function(event) { onOpen(event) }; webSocket.onclose = function(event) { onClose(event) }; webSocket.onmessage = function(event) { onMessage(event) }; function onMessage(event) { document.getElementById('messages').innerHTML += '<br />' + event.data; } function onOpen(event) { document.getElementById('messages').innerHTML = 'Connection established'; } function onClose(event) { document.getElementById('messages').innerHTML += '<br />disconnection'; } function onError(event) { alert(event.data); } function start() { webSocket.send('hello'); return false; } </script> </body> </html>
运行结果
以上这篇websocket++简单使用及实例分析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。