wsserver.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <iostream>
  2. #include <string>
  3. #include <functional>
  4. #include <websocketpp/server.hpp>
  5. #include <websocketpp/config/asio_no_tls.hpp>
  6. using std::cout;
  7. using std::endl;
  8. typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
  9. void http_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
  10. wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl);
  11. std::cout << "body: " << conn->get_request_body() << std::endl;
  12. websocketpp::http::parser::request req = conn->get_request();
  13. std::cout << "method: " << req.get_method() << std::endl;
  14. std::cout << "uri: " << req.get_uri() << std::endl;
  15. // 响应一个hello world页面
  16. std::string body = "<html><body><h1>Hello World</h1></body></html>";
  17. conn->set_body(body);
  18. conn->append_header("Content-Type", "text/html");
  19. conn->set_status(websocketpp::http::status_code::ok);
  20. }
  21. void wsopen_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
  22. cout << "websocket握手成功" << std::endl;
  23. }
  24. void wsclose_callback(wsserver_t *srv, websocketpp::connection_hdl hdl) {
  25. cout << "websocket连接关闭" << endl;
  26. }
  27. void wsmessage_callback(wsserver_t *srv, websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg) {
  28. wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl);
  29. cout << "wsmsg: " << msg->get_payload() << endl;
  30. std::string rsp = "[client]# " + msg->get_payload();
  31. conn->send(rsp, websocketpp::frame::opcode::text);
  32. }
  33. int main()
  34. {
  35. // 1. 实例化server对象
  36. wsserver_t wssrv;
  37. // 2. 设置日志等级
  38. wssrv.set_access_channels(websocketpp::log::alevel::none);
  39. // 3. 初始化asio调度器
  40. wssrv.init_asio();
  41. // 4. 设置回调函数
  42. wssrv.set_http_handler(std::bind(http_callback, &wssrv, std::placeholders::_1));
  43. wssrv.set_open_handler(std::bind(wsopen_callback, &wssrv, std::placeholders::_1));
  44. wssrv.set_close_handler(std::bind(wsclose_callback, &wssrv, std::placeholders::_1));
  45. wssrv.set_message_handler(std::bind(wsmessage_callback, &wssrv, std::placeholders::_1, std::placeholders::_2));
  46. // 5. 设置监听端口
  47. wssrv.listen(8080);
  48. wssrv.set_reuse_addr(true);
  49. // 6. 开始获取新连接
  50. wssrv.start_accept();
  51. // 7. 启动服务器
  52. wssrv.run();
  53. return 0;
  54. }