websocketclient.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /**
  2. * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
  3. * Reserved. MIT License (https://opensource.org/licenses/MIT)
  4. */
  5. /* 2022-2023 by zhaomingwork */
  6. // client for websocket, support multiple threads
  7. // Usage: websocketclient server_ip port wav_path threads_num
  8. #define ASIO_STANDALONE 1
  9. #include <websocketpp/client.hpp>
  10. #include <websocketpp/common/thread.hpp>
  11. #include <websocketpp/config/asio_client.hpp>
  12. #include "audio.h"
  13. #include "nlohmann/json.hpp"
  14. /**
  15. * Define a semi-cross platform helper method that waits/sleeps for a bit.
  16. */
  17. void wait_a_bit() {
  18. #ifdef WIN32
  19. Sleep(1000);
  20. #else
  21. sleep(1);
  22. #endif
  23. }
  24. typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
  25. typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context>
  26. context_ptr;
  27. using websocketpp::lib::bind;
  28. using websocketpp::lib::placeholders::_1;
  29. using websocketpp::lib::placeholders::_2;
  30. context_ptr on_tls_init(websocketpp::connection_hdl) {
  31. context_ptr ctx = websocketpp::lib::make_shared<asio::ssl::context>(
  32. asio::ssl::context::sslv23);
  33. try {
  34. ctx->set_options(
  35. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 |
  36. asio::ssl::context::no_sslv3 | asio::ssl::context::single_dh_use);
  37. } catch (std::exception& e) {
  38. std::cout << e.what() << std::endl;
  39. }
  40. return ctx;
  41. }
  42. // template for tls or not config
  43. template <typename T>
  44. class websocket_client {
  45. public:
  46. // typedef websocketpp::client<T> client;
  47. // typedef websocketpp::client<websocketpp::config::asio_tls_client>
  48. // wss_client;
  49. typedef websocketpp::lib::lock_guard<websocketpp::lib::mutex> scoped_lock;
  50. websocket_client(int is_ssl) : m_open(false), m_done(false) {
  51. // set up access channels to only log interesting things
  52. m_client.clear_access_channels(websocketpp::log::alevel::all);
  53. m_client.set_access_channels(websocketpp::log::alevel::connect);
  54. m_client.set_access_channels(websocketpp::log::alevel::disconnect);
  55. m_client.set_access_channels(websocketpp::log::alevel::app);
  56. // Initialize the Asio transport policy
  57. m_client.init_asio();
  58. // Bind the handlers we are using
  59. using websocketpp::lib::bind;
  60. using websocketpp::lib::placeholders::_1;
  61. m_client.set_open_handler(bind(&websocket_client::on_open, this, _1));
  62. m_client.set_close_handler(bind(&websocket_client::on_close, this, _1));
  63. m_client.set_close_handler(bind(&websocket_client::on_close, this, _1));
  64. m_client.set_message_handler(
  65. [this](websocketpp::connection_hdl hdl, message_ptr msg) {
  66. on_message(hdl, msg);
  67. });
  68. m_client.set_fail_handler(bind(&websocket_client::on_fail, this, _1));
  69. m_client.clear_access_channels(websocketpp::log::alevel::all);
  70. }
  71. void on_message(websocketpp::connection_hdl hdl, message_ptr msg) {
  72. const std::string& payload = msg->get_payload();
  73. switch (msg->get_opcode()) {
  74. case websocketpp::frame::opcode::text:
  75. std::cout << "on_message=" << payload << std::endl;
  76. }
  77. }
  78. // This method will block until the connection is complete
  79. void run(const std::string& uri, const std::string& wav_path) {
  80. // Create a new connection to the given URI
  81. websocketpp::lib::error_code ec;
  82. typename websocketpp::client<T>::connection_ptr con =
  83. m_client.get_connection(uri, ec);
  84. if (ec) {
  85. m_client.get_alog().write(websocketpp::log::alevel::app,
  86. "Get Connection Error: " + ec.message());
  87. return;
  88. }
  89. this->wav_path = std::move(wav_path);
  90. // Grab a handle for this connection so we can talk to it in a thread
  91. // safe manor after the event loop starts.
  92. m_hdl = con->get_handle();
  93. // Queue the connection. No DNS queries or network connections will be
  94. // made until the io_service event loop is run.
  95. m_client.connect(con);
  96. // Create a thread to run the ASIO io_service event loop
  97. websocketpp::lib::thread asio_thread(&websocketpp::client<T>::run,
  98. &m_client);
  99. send_wav_data();
  100. asio_thread.join();
  101. }
  102. // The open handler will signal that we are ready to start sending data
  103. void on_open(websocketpp::connection_hdl) {
  104. m_client.get_alog().write(websocketpp::log::alevel::app,
  105. "Connection opened, starting data!");
  106. scoped_lock guard(m_lock);
  107. m_open = true;
  108. }
  109. // The close handler will signal that we should stop sending data
  110. void on_close(websocketpp::connection_hdl) {
  111. m_client.get_alog().write(websocketpp::log::alevel::app,
  112. "Connection closed, stopping data!");
  113. scoped_lock guard(m_lock);
  114. m_done = true;
  115. }
  116. // The fail handler will signal that we should stop sending data
  117. void on_fail(websocketpp::connection_hdl) {
  118. m_client.get_alog().write(websocketpp::log::alevel::app,
  119. "Connection failed, stopping data!");
  120. scoped_lock guard(m_lock);
  121. m_done = true;
  122. }
  123. // send wav to server
  124. void send_wav_data() {
  125. uint64_t count = 0;
  126. std::stringstream val;
  127. funasr::Audio audio(1);
  128. int32_t sampling_rate = 16000;
  129. if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate)) {
  130. std::cout << "error in load wav" << std::endl;
  131. return;
  132. }
  133. float* buff;
  134. int len;
  135. int flag = 0;
  136. bool wait = false;
  137. while (1) {
  138. {
  139. scoped_lock guard(m_lock);
  140. // If the connection has been closed, stop generating data
  141. if (m_done) {
  142. break;
  143. }
  144. // If the connection hasn't been opened yet wait a bit and retry
  145. if (!m_open) {
  146. wait = true;
  147. } else {
  148. break;
  149. }
  150. }
  151. if (wait) {
  152. std::cout << "wait.." << m_open << std::endl;
  153. wait_a_bit();
  154. continue;
  155. }
  156. }
  157. websocketpp::lib::error_code ec;
  158. nlohmann::json jsonbegin;
  159. nlohmann::json chunk_size = nlohmann::json::array();
  160. chunk_size.push_back(5);
  161. chunk_size.push_back(0);
  162. chunk_size.push_back(5);
  163. jsonbegin["chunk_size"] = chunk_size;
  164. jsonbegin["chunk_interval"] = 10;
  165. jsonbegin["wav_name"] = "damo";
  166. jsonbegin["is_speaking"] = true;
  167. m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
  168. ec);
  169. // fetch wav data use asr engine api
  170. while (audio.Fetch(buff, len, flag) > 0) {
  171. short iArray[len];
  172. // convert float -1,1 to short -32768,32767
  173. for (size_t i = 0; i < len; ++i) {
  174. iArray[i] = (short)(buff[i] * 32767);
  175. }
  176. // send data to server
  177. m_client.send(m_hdl, iArray, len * sizeof(short),
  178. websocketpp::frame::opcode::binary, ec);
  179. std::cout << "sended data len=" << len * sizeof(short) << std::endl;
  180. // The most likely error that we will get is that the connection is
  181. // not in the right state. Usually this means we tried to send a
  182. // message to a connection that was closed or in the process of
  183. // closing. While many errors here can be easily recovered from,
  184. // in this simple example, we'll stop the data loop.
  185. if (ec) {
  186. m_client.get_alog().write(websocketpp::log::alevel::app,
  187. "Send Error: " + ec.message());
  188. break;
  189. }
  190. wait_a_bit();
  191. }
  192. nlohmann::json jsonresult;
  193. jsonresult["is_speaking"] = false;
  194. m_client.send(m_hdl, jsonresult.dump(), websocketpp::frame::opcode::text,
  195. ec);
  196. wait_a_bit();
  197. }
  198. websocketpp::client<T> m_client;
  199. private:
  200. websocketpp::connection_hdl m_hdl;
  201. websocketpp::lib::mutex m_lock;
  202. std::string wav_path;
  203. bool m_open;
  204. bool m_done;
  205. };
  206. int main(int argc, char* argv[]) {
  207. if (argc < 6) {
  208. printf("Usage: %s server_ip port wav_path threads_num is_ssl\n", argv[0]);
  209. exit(-1);
  210. }
  211. std::string server_ip = argv[1];
  212. std::string port = argv[2];
  213. std::string wav_path = argv[3];
  214. int threads_num = atoi(argv[4]);
  215. int is_ssl = atoi(argv[5]);
  216. std::vector<websocketpp::lib::thread> client_threads;
  217. std::string uri = "";
  218. if (is_ssl == 1) {
  219. uri = "wss://" + server_ip + ":" + port;
  220. } else {
  221. uri = "ws://" + server_ip + ":" + port;
  222. }
  223. for (size_t i = 0; i < threads_num; i++) {
  224. client_threads.emplace_back([uri, wav_path, is_ssl]() {
  225. if (is_ssl == 1) {
  226. websocket_client<websocketpp::config::asio_tls_client> c(is_ssl);
  227. c.m_client.set_tls_init_handler(bind(&on_tls_init, ::_1));
  228. c.run(uri, wav_path);
  229. } else {
  230. websocket_client<websocketpp::config::asio_client> c(is_ssl);
  231. c.run(uri, wav_path);
  232. }
  233. });
  234. }
  235. for (auto& t : client_threads) {
  236. t.join();
  237. }
  238. }