websocketclient.cpp 7.3 KB

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