File: handler_switch.cpp

package info (click to toggle)
websocketpp 0.8.2%2Bgit20250909-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,712 kB
  • sloc: cpp: 20,512; makefile: 18
file content (42 lines) | stat: -rw-r--r-- 1,286 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.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::ref;

void custom_on_msg(server & s, connection_hdl hdl, server::message_ptr msg) {
        std::cout << "Message sent to custom handler" << std::endl;
}

void default_on_msg(server & s, connection_hdl hdl, server::message_ptr msg) {
    std::cout << "Message sent to default handler" << std::endl;

    if (msg->get_payload() == "upgrade") {
        // Upgrade our connection_hdl to a full connection_ptr
        server::connection_ptr con = s.get_con_from_hdl(hdl);

        // Change the on message handler for this connection only to
        // custom_on_mesage
        con->set_message_handler(bind(&custom_on_msg,ref(s),::_1,::_2));
        std::cout << "Upgrading connection to custom handler" << std::endl;
    }
}

int main() {
    server s;

    s.set_message_handler(bind(&default_on_msg,ref(s),::_1,::_2));

    s.init_asio();
    s.listen(9002);
    s.start_accept(NULL); // ignore errors to keep example code consise

    s.run();
}