C++ websocket服務器與客戶端庫websocketpp


websocketpp
https://github.com/zaphoyd/websocketpp
https://docs.websocketpp.org/getting_started.html

倉庫包含如下幾個目錄:

  • docs: 文檔
  • examples: 示例程序演示如何為WebSocket客戶端和服務器構建一些常用模式的基本版本。
  • test單元測試確認您的代碼正常工作,並幫助檢測平台特定的問題。
  • tutorials: 一組示例程序的詳細演練。
  • websocketpp: 所有庫代碼和默認配置文件。

WebSocket ++是僅包含頭文件的庫。 您可以通過在項目的包含路徑中包含websocketpp源目錄,並在程序中包含適當的WebSocket++頭文件,來開始使用它。 您可能還需要包含和/或鏈接到適當的Boost/系統庫。

examples下有echo_serverecho_client,一般作為入門的例子。
下面在Windows上來運行這個例子。
首先,下載boosthttps://www.boost.org/users/download/
接下來編譯boost:
打開命令行,運行bootstrap.bat
接下來運行b2.exe
不出意外的話,就編好了(我這里都是默認配置來編譯的,使用的是VS2019)

VS2019中新建websocketpp_server console
刪掉main.cpp,將echo_server.cpp拷貝過來加入到工程中去

VS2019中新建websocketpp_client console
刪掉main.cpp,將echo_client.cpp拷貝過來加入到工程中去

工程設置:
Include路徑:
D:\GitWork\boost_1_72_0
D:\GitWork\websocketpp-master
Lib路徑:
D:\GitWork\boost_1_72_0\stage\lib
鏈接libboost_date_time-vc142-mt-gd-x64-1_72.lib

Debug x64配置構建運行:

可以使用在線WebSocket網站進行測試

服務端收到信息:

如果要在Qt中使用,可參考以下pro配置:

QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle

DEFINES += QT_DEPRECATED_WARNINGS

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

HEADERS += \
    echo_handler.hpp   # 沒用到,里面內容可注釋掉

SOURCES += \
    echo_server.cpp

win32: LIBS += -L$$PWD/../../../boost_1_72_0/stage/lib/ -llibboost_date_time-vc142-mt-gd-x64-1_72
win32: LIBS += -lWs2_32 \
            -lwsock32
INCLUDEPATH += $$PWD/../../
INCLUDEPATH += $$PWD/../../../boost_1_72_0
DEPENDPATH += $$PWD/../../../boost_1_72_0/stage

關於主動發送信息,可以使用send方法,可以開一個線程,如果有內容,就發送,broadcast_server可以參考一下:

#include <websocketpp/config/asio_no_tls.hpp>

#include <websocketpp/server.hpp>

#include <iostream>
#include <set>

/*#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;

/* on_open insert connection_hdl into channel
 * on_close remove connection_hdl from channel
 * on_message queue send to all channels
 */

enum action_type {
    SUBSCRIBE,
    UNSUBSCRIBE,
    MESSAGE
};

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

    action_type type;
    websocketpp::connection_hdl hdl;
    server::message_ptr msg;
};

class broadcast_server {
public:
    broadcast_server() {
        // Initialize Asio Transport
        m_server.init_asio();

        // Register handler callbacks
        m_server.set_open_handler(bind(&broadcast_server::on_open,this,::_1));
        m_server.set_close_handler(bind(&broadcast_server::on_close,this,::_1));
        m_server.set_message_handler(bind(&broadcast_server::on_message,this,::_1,::_2));
    }

    void run(uint16_t port) {
        // listen on specified port
        m_server.listen(port);

        // Start the server accept loop
        m_server.start_accept();

        // Start the ASIO io_service run loop
        try {
            m_server.run();
        } catch (const std::exception & e) {
            std::cout << e.what() << std::endl;
        }
    }

    void on_open(connection_hdl hdl) {
        {
            lock_guard<mutex> guard(m_action_lock);
            //std::cout << "on_open" << std::endl;
            m_actions.push(action(SUBSCRIBE,hdl));
        }
        m_action_cond.notify_one();
    }

    void on_close(connection_hdl hdl) {
        {
            lock_guard<mutex> guard(m_action_lock);
            //std::cout << "on_close" << std::endl;
            m_actions.push(action(UNSUBSCRIBE,hdl));
        }
        m_action_cond.notify_one();
    }

    void on_message(connection_hdl hdl, server::message_ptr msg) {
        // queue message up for sending by processing thread
        {
            lock_guard<mutex> guard(m_action_lock);
            //std::cout << "on_message" << std::endl;
            m_actions.push(action(MESSAGE,hdl,msg));
        }
        m_action_cond.notify_one();
    }

    void process_messages() {
        while(1) {
            unique_lock<mutex> lock(m_action_lock);

            while(m_actions.empty()) {
                m_action_cond.wait(lock);
            }

            action a = m_actions.front();
            m_actions.pop();

            lock.unlock();

            if (a.type == SUBSCRIBE) {
                lock_guard<mutex> guard(m_connection_lock);
                m_connections.insert(a.hdl);
            } else if (a.type == UNSUBSCRIBE) {
                lock_guard<mutex> guard(m_connection_lock);
                m_connections.erase(a.hdl);
            } else if (a.type == MESSAGE) {
                lock_guard<mutex> guard(m_connection_lock);

                con_list::iterator it;
                for (it = m_connections.begin(); it != m_connections.end(); ++it) {
                    m_server.send(*it,a.msg);
                }
            } else {
                // undefined.
            }
        }
    }
private:
    typedef std::set<connection_hdl,std::owner_less<connection_hdl> > con_list;

    server m_server;
    con_list m_connections;
    std::queue<action> m_actions;

    mutex m_action_lock;
    mutex m_connection_lock;
    condition_variable m_action_cond;
};

int main() {
    try {
    broadcast_server server_instance;

    // Start a thread to run the processing loop
    thread t(bind(&broadcast_server::process_messages,&server_instance));

    // Run the asio loop with the main thread
    server_instance.run(9002);

    t.join();

    } catch (websocketpp::exception const & e) {
        std::cout << e.what() << std::endl;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM