当前位置:   article > 正文

C/C++ 实现的websocket客户端和服务器_c++ 编译 websocket exe 启动

c++ 编译 websocket exe 启动

领导安排实现一个websocket客户端做测试用,因为工位电脑上的环境只有vs2019和boost1.78.0,所以只能基于boost.beast开发。

擅长Qt并且有Qt开发环境的用QWebsocket更方便。

官方的example中仅仅输出到控制台,而且不支持中文,这里我加入了ansi到utf8的转换,使用utf8就能正常解析中文。

注:项目需包含boost库

客户端代码:

  1. #include<time.h>
  2. #include <boost/beast/core.hpp>
  3. #include <boost/beast/websocket.hpp>
  4. #include <boost/asio/connect.hpp>
  5. #include <boost/asio/ip/tcp.hpp>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <string>
  9. #include <locale>
  10. #include <codecvt>
  11. namespace beast = boost::beast; // from <boost/beast.hpp>
  12. namespace http = beast::http; // from <boost/beast/http.hpp>
  13. namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
  14. namespace net = boost::asio; // from <boost/asio.hpp>
  15. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  16. std::wstring string_to_wstring(const std::string &s)
  17. {
  18. using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
  19. static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
  20. return conv.from_bytes(s);
  21. }
  22. std::string wstring_to_string(const std::wstring &s)
  23. {
  24. using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
  25. static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
  26. return conv.to_bytes(s);
  27. }
  28. std::string ansi_to_utf8(const std::string &s)
  29. {
  30. static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
  31. return conv.to_bytes(string_to_wstring(s));
  32. }
  33. std::string utf8_to_ansi(const std::string& s)
  34. {
  35. static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
  36. return wstring_to_string(conv.from_bytes(s));
  37. }
  38. int main(int argc, char** argv)
  39. {
  40. int num = 0;//接收到包的个数
  41. try
  42. {
  43. net::io_context ioc;
  44. tcp::resolver resolver{ ioc };
  45. websocket::stream<tcp::socket> ws{ ioc };
  46. auto const address = net::ip::make_address("10.73.0.170"); //服务器地址
  47. auto const port = static_cast<unsigned short>(std::atoi("20000"));//服务器端口号
  48. tcp::endpoint endpoint{ address, port };
  49. auto const results = resolver.resolve(endpoint);
  50. // 在我们从查找中获得的IP地址上建立连接
  51. net::connect(ws.next_layer(), results.begin(), results.end());
  52. ws.set_option(websocket::stream_base::decorator(
  53. [](websocket::request_type& req)
  54. {
  55. req.set(http::field::user_agent,
  56. std::string(BOOST_BEAST_VERSION_STRING) +
  57. " websocket-client-coro");
  58. }));
  59. ws.handshake("10.73.0.170", "/"); //发送握手消息
  60. while (true)
  61. {
  62. beast::flat_buffer buffer;//创建一个缓冲区用于存放接收到的消息
  63. ws.read(buffer);// 读取一条消息到缓冲区
  64. std::string out;
  65. out = beast::buffers_to_string(buffer.cdata());
  66. std::cout << utf8_to_ansi(out) << std::endl; //输出消息到控制台显示
  67. //解析json数据包
  68. if (out != "") //未解析json,只是判断内容是否为空
  69. {
  70. std::string text = "{\"result\": 0}";//发送的消息内容,以一个json数据包的格式
  71. ws.write(net::buffer(ansi_to_utf8(text))); // 发送消息
  72. num++;//增加计数
  73. //当前时间
  74. time_t now = time(NULL);
  75. tm* tm_t = localtime(&now);
  76. std::stringstream ss;
  77. ss << tm_t->tm_year + 1900 << "-" << tm_t->tm_mon + 1 << "-" << tm_t->tm_mday
  78. << " " << tm_t->tm_hour << ":" << tm_t->tm_min << ":" << tm_t->tm_sec;
  79. std::cout << "当前时间:" << ss.str() << ",第 " << num << "个"<<std::endl;
  80. }
  81. }
  82. ws.close(websocket::close_code::normal);// 关闭WebSocket连接
  83. }
  84. catch (std::exception const& e)
  85. {
  86. std::cerr << "Error: " << e.what() << std::endl;
  87. return EXIT_FAILURE;
  88. }
  89. return EXIT_SUCCESS;
  90. }

服务器代码:

  1. #include <boost/beast/core.hpp>
  2. #include <boost/beast/websocket.hpp>
  3. #include <boost/asio/ip/tcp.hpp>
  4. #include <cstdlib>
  5. #include <functional>
  6. #include <iostream>
  7. #include <string>
  8. #include <thread>
  9. #include <codecvt>
  10. namespace beast = boost::beast; // from <boost/beast.hpp>
  11. namespace http = beast::http; // from <boost/beast/http.hpp>
  12. namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
  13. namespace net = boost::asio; // from <boost/asio.hpp>
  14. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  15. std::wstring string_to_wstring(const std::string& s)
  16. {
  17. using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
  18. static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
  19. return conv.from_bytes(s);
  20. }
  21. std::string wstring_to_string(const std::wstring& s)
  22. {
  23. using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
  24. static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
  25. return conv.to_bytes(s);
  26. }
  27. std::string ansi_to_utf8(const std::string& s)
  28. {
  29. static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
  30. return conv.to_bytes(string_to_wstring(s));
  31. }
  32. std::string utf8_to_ansi(const std::string& s)
  33. {
  34. static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
  35. return wstring_to_string(conv.from_bytes(s));
  36. }
  37. void do_session(tcp::socket& socket)
  38. {
  39. try
  40. {
  41. websocket::stream<tcp::socket> ws{ std::move(socket) };
  42. ws.set_option(websocket::stream_base::decorator(
  43. [](websocket::response_type& res)
  44. {
  45. res.set(http::field::server,
  46. std::string(BOOST_BEAST_VERSION_STRING) +
  47. " websocket-server-sync");
  48. }));
  49. ws.accept();//等待客户端连接
  50. for (;;)
  51. {
  52. std::string text = "{\"send\": 123}"; // 发送的消息内容,以一个json数据包的格式
  53. ws.write(net::buffer(ansi_to_utf8(text)));// 发送消息
  54. beast::flat_buffer buffer;// 这个缓冲区将保存传入的消息
  55. ws.read(buffer);// 读取一条消息
  56. auto out = beast::buffers_to_string(buffer.cdata());
  57. std::cout << utf8_to_ansi(out) << std::endl;
  58. Sleep(1000); //等待1
  59. /*
  60. // 将读取到的消息再发送回客户端
  61. ws.text(ws.got_text());
  62. ws.write(buffer.data());
  63. */
  64. }
  65. }
  66. catch (beast::system_error const& se)
  67. {
  68. if (se.code() != websocket::error::closed)
  69. std::cerr << "Error: " << se.code().message() << std::endl;
  70. }
  71. catch (std::exception const& e)
  72. {
  73. std::cerr << "Error: " << e.what() << std::endl;
  74. }
  75. }
  76. int main(int argc, char* argv[])
  77. {
  78. try
  79. {
  80. auto const address = net::ip::make_address("10.73.0.170");//绑定ip地址
  81. auto const port = static_cast<unsigned short>(std::atoi("20000"));//绑定端口号
  82. net::io_context ioc{ 1 };
  83. tcp::acceptor acceptor{ ioc,{ address, port } };
  84. for (;;)
  85. {
  86. tcp::socket socket{ ioc };
  87. acceptor.accept(socket);
  88. // 开启线程等待客户端的连接请求
  89. std::thread{ std::bind(&do_session,std::move(socket)) }.detach();
  90. }
  91. }
  92. catch (const std::exception & e)
  93. {
  94. std::cerr << "Error: " << e.what() << std::endl;
  95. return EXIT_FAILURE;
  96. }
  97. }

联调效果:

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号