1. 程式人生 > >在VS2015下配置websocket++,並用C++搭建一個簡單的客戶端

在VS2015下配置websocket++,並用C++搭建一個簡單的客戶端

簡介

  • 最近在做一個專案,需要在C++中通過WebSocket和伺服器進行通訊,但我們在C++中並不能直接使用WebSocket,於是上網搜尋後發現websocket++這個庫很合適。
  • Websocket是基於HTTP協議的,或者說借用了HTTP的協議來完成一部分握手,並且它很好的支援了長連線,相較於ajax輪詢和long poll更加節省資源。

準備工作

配置方法

  • 第一步,新建一個工程
    將專案屬性調整為Release x64模式,如下圖所示

這裡寫圖片描述

  • 第二步,開啟 專案—專案屬性 視窗,選擇VC++目錄
    在“包含目錄”下新增boost和websocket++的目錄,如下圖所示

這裡寫圖片描述

  • 第三步,在“庫目錄”下新增boost的lib包目錄

這裡寫圖片描述

  • 點選“應用”,然後“確定”,OK大功告成。

一個簡單的WebSocket客戶端

  • 我們到下載的websocket++資料夾目錄下的websocketpp-master\examples\echo_client中的C++程式碼檔案拷貝出來,在工程裡測試執行即可,順便附上程式碼:
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <iostream>
typedef websocketpp::client<websocketpp::config::asio_client> client; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; // pull out the type of messages sent by our config typedef websocketpp::config::asio_client::message_type::ptr message_ptr; // This message handler will be invoked once for each incoming message. It
// prints the message and then sends a copy of the message back to the server. void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) { std::cout << "on_message called with hdl: " << hdl.lock().get() << " and message: " << msg->get_payload() << std::endl; websocketpp::lib::error_code ec; c->send(hdl, msg->get_payload(), msg->get_opcode(), ec); if (ec) { std::cout << "Echo failed because: " << ec.message() << std::endl; } } int main(int argc, char* argv[]) { // Create a client endpoint client c; std::string uri = "ws://這裡附上你自己的ws地址"; try { // Set logging to be pretty verbose (everything except message payloads) c.set_access_channels(websocketpp::log::alevel::all); c.clear_access_channels(websocketpp::log::alevel::frame_payload); // Initialize ASIO c.init_asio(); // Register our message handler c.set_message_handler(bind(&on_message,&c,::_1,::_2)); websocketpp::lib::error_code ec; client::connection_ptr con = c.get_connection(uri, ec); if (ec) { std::cout << "could not create connection because: " << ec.message() << std::endl; return 0; } // Note that connect here only requests a connection. No network messages are // exchanged until the event loop starts running in the next line. c.connect(con); // Start the ASIO io_service run loop // this will cause a single connection to be made to the server. c.run() // will exit when this connection is closed. c.run(); } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } }

至此,我們就完成了websocket++的基本配置。

PS.如果編譯器提示你 “錯誤:後面有::的名稱一定是類名或名稱空間名”或者 其他一些奇奇怪怪的錯誤,那多半是websocket++和boost的附加目錄沒有配置好