websocketclient.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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_no_tls_client.hpp>
  12. #include "audio.h"
  13. /**
  14. * Define a semi-cross platform helper method that waits/sleeps for a bit.
  15. */
  16. void wait_a_bit() {
  17. #ifdef WIN32
  18. Sleep(1000);
  19. #else
  20. sleep(1);
  21. #endif
  22. }
  23. typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
  24. class websocket_client {
  25. public:
  26. typedef websocketpp::client<websocketpp::config::asio_client> client;
  27. typedef websocketpp::lib::lock_guard<websocketpp::lib::mutex> scoped_lock;
  28. websocket_client() : m_open(false), m_done(false) {
  29. // set up access channels to only log interesting things
  30. m_client.clear_access_channels(websocketpp::log::alevel::all);
  31. m_client.set_access_channels(websocketpp::log::alevel::connect);
  32. m_client.set_access_channels(websocketpp::log::alevel::disconnect);
  33. m_client.set_access_channels(websocketpp::log::alevel::app);
  34. // Initialize the Asio transport policy
  35. m_client.init_asio();
  36. // Bind the handlers we are using
  37. using websocketpp::lib::bind;
  38. using websocketpp::lib::placeholders::_1;
  39. m_client.set_open_handler(bind(&websocket_client::on_open, this, _1));
  40. m_client.set_close_handler(bind(&websocket_client::on_close, this, _1));
  41. m_client.set_close_handler(bind(&websocket_client::on_close, this, _1));
  42. m_client.set_message_handler(
  43. [this](websocketpp::connection_hdl hdl, message_ptr msg) {
  44. on_message(hdl, msg);
  45. });
  46. m_client.set_fail_handler(bind(&websocket_client::on_fail, this, _1));
  47. m_client.clear_access_channels(websocketpp::log::alevel::all);
  48. }
  49. void on_message(websocketpp::connection_hdl hdl, message_ptr msg) {
  50. const std::string& payload = msg->get_payload();
  51. switch (msg->get_opcode()) {
  52. case websocketpp::frame::opcode::text:
  53. std::cout << "on_message=" << payload << std::endl;
  54. }
  55. }
  56. // This method will block until the connection is complete
  57. void run(const std::string& uri, const std::string& wav_path) {
  58. // Create a new connection to the given URI
  59. websocketpp::lib::error_code ec;
  60. client::connection_ptr con = m_client.get_connection(uri, ec);
  61. if (ec) {
  62. m_client.get_alog().write(websocketpp::log::alevel::app,
  63. "Get Connection Error: " + ec.message());
  64. return;
  65. }
  66. this->wav_path = std::move(wav_path);
  67. // Grab a handle for this connection so we can talk to it in a thread
  68. // safe manor after the event loop starts.
  69. m_hdl = con->get_handle();
  70. // Queue the connection. No DNS queries or network connections will be
  71. // made until the io_service event loop is run.
  72. m_client.connect(con);
  73. // Create a thread to run the ASIO io_service event loop
  74. websocketpp::lib::thread asio_thread(&client::run, &m_client);
  75. send_wav_data();
  76. asio_thread.join();
  77. }
  78. // The open handler will signal that we are ready to start sending data
  79. void on_open(websocketpp::connection_hdl) {
  80. m_client.get_alog().write(websocketpp::log::alevel::app,
  81. "Connection opened, starting data!");
  82. scoped_lock guard(m_lock);
  83. m_open = true;
  84. }
  85. // The close handler will signal that we should stop sending data
  86. void on_close(websocketpp::connection_hdl) {
  87. m_client.get_alog().write(websocketpp::log::alevel::app,
  88. "Connection closed, stopping data!");
  89. scoped_lock guard(m_lock);
  90. m_done = true;
  91. }
  92. // The fail handler will signal that we should stop sending data
  93. void on_fail(websocketpp::connection_hdl) {
  94. m_client.get_alog().write(websocketpp::log::alevel::app,
  95. "Connection failed, stopping data!");
  96. scoped_lock guard(m_lock);
  97. m_done = true;
  98. }
  99. // send wav to server
  100. void send_wav_data() {
  101. uint64_t count = 0;
  102. std::stringstream val;
  103. Audio audio(1);
  104. int32_t sampling_rate = 16000;
  105. if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate)) {
  106. std::cout << "error in load wav" << std::endl;
  107. return;
  108. }
  109. float* buff;
  110. int len;
  111. int flag = 0;
  112. bool wait = false;
  113. while (1) {
  114. {
  115. scoped_lock guard(m_lock);
  116. // If the connection has been closed, stop generating data
  117. if (m_done) {
  118. break;
  119. }
  120. // If the connection hasn't been opened yet wait a bit and retry
  121. if (!m_open) {
  122. wait = true;
  123. } else {
  124. break;
  125. }
  126. }
  127. if (wait) {
  128. std::cout << "wait.." << m_open << std::endl;
  129. wait_a_bit();
  130. continue;
  131. }
  132. }
  133. websocketpp::lib::error_code ec;
  134. // fetch wav data use asr engine api
  135. while (audio.Fetch(buff, len, flag) > 0) {
  136. short iArray[len];
  137. // convert float -1,1 to short -32768,32767
  138. for (size_t i = 0; i < len; ++i) {
  139. iArray[i] = (short)(buff[i] * 32767);
  140. }
  141. // send data to server
  142. m_client.send(m_hdl, iArray, len * sizeof(short),
  143. websocketpp::frame::opcode::binary, ec);
  144. std::cout << "sended data len=" << len * sizeof(short) << std::endl;
  145. // The most likely error that we will get is that the connection is
  146. // not in the right state. Usually this means we tried to send a
  147. // message to a connection that was closed or in the process of
  148. // closing. While many errors here can be easily recovered from,
  149. // in this simple example, we'll stop the data loop.
  150. if (ec) {
  151. m_client.get_alog().write(websocketpp::log::alevel::app,
  152. "Send Error: " + ec.message());
  153. break;
  154. }
  155. wait_a_bit();
  156. }
  157. m_client.send(m_hdl, "Done", websocketpp::frame::opcode::text, ec);
  158. wait_a_bit();
  159. }
  160. private:
  161. client m_client;
  162. websocketpp::connection_hdl m_hdl;
  163. websocketpp::lib::mutex m_lock;
  164. std::string wav_path;
  165. bool m_open;
  166. bool m_done;
  167. };
  168. int main(int argc, char* argv[]) {
  169. if (argc < 5) {
  170. printf("Usage: %s server_ip port wav_path threads_num\n", argv[0]);
  171. exit(-1);
  172. }
  173. std::string server_ip = argv[1];
  174. std::string port = argv[2];
  175. std::string wav_path = argv[3];
  176. int threads_num = atoi(argv[4]);
  177. std::vector<websocketpp::lib::thread> client_threads;
  178. std::string uri = "ws://" + server_ip + ":" + port;
  179. for (size_t i = 0; i < threads_num; i++) {
  180. client_threads.emplace_back([uri, wav_path]() {
  181. websocket_client c;
  182. c.run(uri, wav_path);
  183. });
  184. }
  185. for (auto& t : client_threads) {
  186. t.join();
  187. }
  188. }