使用websocketpp編寫websocket的服務端程序


       webscoketpp是一個基於boost庫的websocket實現,實現的相對完善一些。主頁地址:http://www.zaphoyd.com/websocketpp。

       因為做項目需要用到,所以簡單做了下分析,下面是關於如何編寫server的介紹:

       1. 自定義一個server_handler類,繼承自websocketpp::server::handler(簡稱ws_hander);

             1. ws_handler是在endpoint_tarits中定義的一個類

1                  class handler: public role_type::handler_interface,
2                  public socket_type::handler_interface

                其中虛函數有:

 1                 virtual void validate(connection_ptr con) {}
 2 
 3                 virtual void on_open(connection_ptr con) {}
 4 
 5                 virtual void on_close(connection_ptr con) {}
 6 
 7                 virtual void on_fail(connection_ptr con) {}
 8 
 9                 virtual void on_message(connection_ptr con,message::data_ptr) {}
10 
11                 virtual bool on_ping(connection_ptr con,std::string) {return true;}
12 
13                 virtual void on_pong(connection_ptr con,std::string) {}
14 
15                 virtual void on_pong_timeout(connection_ptr con,std::string) {}
16 
17                 virtual void http(connection_ptr con) {}

 

             可以在server_handler中重寫這些函數,處理相應的邏輯。

       2. hander_ptr = new server_hander();

       3. 聲明一個websocketpp::server的對象test_server,以handler_ptr為參數;

              1. websocketpp::server 是endpoint<websocketpp::role::server, websocketpp::socket::plain>的重定義

              2. 開放接口有:

 1    handler_ptr get_handler();
 2      void set_handler(handler_ptr new_handler);
 3      size_t get_threshold();
 4      void set_threshold();
 5      void close_all(close::status::value code = close::status::GOING_AWAY, const std::string& reason = "");
 6      void stop(bool clean = true, close::status::value code = close::status::GOING_AWAY, const std::string& reason = "");

                繼承自role::server的:

1                     void listen(uint16_t port, size_t n = 1);
2 
3                     void listen(const boost::asio::ip::tcp::endpoint& e, size_t num_threads = 1);
4 
5                     void listen(const std::string &host, const std::string &service, size_t n = 1);
6 
7                     void listen(const InternetProtocol &internet_protocol, uint16_t port, size_t n = 1);

       4. 啟動監聽: test_server.listen(port_n);


免責聲明!

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



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