main.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * libdatachannel client example
  3. * Copyright (c) 2019-2020 Paul-Louis Ageneau
  4. * Copyright (c) 2019 Murat Dogan
  5. * Copyright (c) 2020 Will Munn
  6. * Copyright (c) 2020 Nico Chatzi
  7. * Copyright (c) 2020 Lara Mackey
  8. * Copyright (c) 2020 Erik Cota-Robles
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version 2
  13. * of the License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. #include "rtc/rtc.hpp"
  24. #include <nlohmann/json.hpp>
  25. #include <algorithm>
  26. #include <iostream>
  27. #include <memory>
  28. #include <random>
  29. #include <thread>
  30. #include <unordered_map>
  31. #include "parse_cl.h"
  32. using namespace rtc;
  33. using namespace std;
  34. using namespace std::chrono_literals;
  35. using json = nlohmann::json;
  36. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  37. unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
  38. unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
  39. string localId;
  40. bool echoDataChannelMessages = false;
  41. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  42. weak_ptr<WebSocket> wws, string id);
  43. void confirmOnStdout(bool echoed, string id, string type, size_t length);
  44. string randomId(size_t length);
  45. int main(int argc, char **argv) {
  46. Cmdline *params = nullptr;
  47. try {
  48. params = new Cmdline(argc, argv);
  49. } catch (const std::range_error&e) {
  50. std::cout<< e.what() << '\n';
  51. delete params;
  52. return -1;
  53. }
  54. rtc::InitLogger(LogLevel::Debug);
  55. Configuration config;
  56. string stunServer = "";
  57. if (params->noStun()) {
  58. cout << "No stun server is configured. Only local hosts and public IP addresses suported." << endl;
  59. } else {
  60. if (params->stunServer().substr(0,5).compare("stun:") != 0) {
  61. stunServer = "stun:";
  62. }
  63. stunServer += params->stunServer() + ":" + to_string(params->stunPort());
  64. cout << "Stun server is " << stunServer << endl;
  65. config.iceServers.emplace_back(stunServer);
  66. }
  67. localId = randomId(4);
  68. cout << "The local ID is: " << localId << endl;
  69. echoDataChannelMessages = params->echoDataChannelMessages();
  70. cout << "Received data channel messages will be "
  71. << (echoDataChannelMessages ? "echoed back to sender" : "printed to stdout") << endl;
  72. auto ws = make_shared<WebSocket>();
  73. ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
  74. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  75. ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
  76. ws->onMessage([&](variant<binary, string> data) {
  77. if (!holds_alternative<string>(data))
  78. return;
  79. json message = json::parse(get<string>(data));
  80. auto it = message.find("id");
  81. if (it == message.end())
  82. return;
  83. string id = it->get<string>();
  84. it = message.find("type");
  85. if (it == message.end())
  86. return;
  87. string type = it->get<string>();
  88. shared_ptr<PeerConnection> pc;
  89. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  90. pc = jt->second;
  91. } else if (type == "offer") {
  92. cout << "Answering to " + id << endl;
  93. pc = createPeerConnection(config, ws, id);
  94. } else {
  95. return;
  96. }
  97. if (type == "offer" || type == "answer") {
  98. auto sdp = message["description"].get<string>();
  99. pc->setRemoteDescription(Description(sdp, type));
  100. } else if (type == "candidate") {
  101. auto sdp = message["candidate"].get<string>();
  102. auto mid = message["mid"].get<string>();
  103. pc->addRemoteCandidate(Candidate(sdp, mid));
  104. }
  105. });
  106. string wsPrefix = "";
  107. if (params->webSocketServer().substr(0,5).compare("ws://") != 0) {
  108. wsPrefix = "ws://";
  109. }
  110. const string url = wsPrefix + params->webSocketServer() + ":" +
  111. to_string(params->webSocketPort()) + "/" + localId;
  112. cout << "Url is " << url << endl;
  113. ws->open(url);
  114. cout << "Waiting for signaling to be connected..." << endl;
  115. while (!ws->isOpen()) {
  116. if (ws->isClosed())
  117. return 1;
  118. this_thread::sleep_for(100ms);
  119. }
  120. while (true) {
  121. string id;
  122. cout << "Enter a remote ID to send an offer:" << endl;
  123. cin >> id;
  124. cin.ignore();
  125. if (id.empty())
  126. break;
  127. if (id == localId)
  128. continue;
  129. cout << "Offering to " + id << endl;
  130. auto pc = createPeerConnection(config, ws, id);
  131. // We are the offerer, so create a data channel to initiate the process
  132. const string label = "test";
  133. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  134. auto dc = pc->createDataChannel(label);
  135. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  136. cout << "DataChannel from " << id << " open" << endl;
  137. if (auto dc = wdc.lock())
  138. dc->send("Hello from " + localId);
  139. });
  140. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  141. dc->onMessage([id, wdc = make_weak_ptr(dc)](const variant<binary, string> &message) {
  142. static bool firstMessage = true;
  143. if (holds_alternative<string>(message) && (!echoDataChannelMessages || firstMessage)) {
  144. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  145. firstMessage = false;
  146. } else if (echoDataChannelMessages) {
  147. bool echoed = false;
  148. if (auto dc = wdc.lock()) {
  149. dc->send(message);
  150. echoed = true;
  151. }
  152. confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
  153. get<string>(message).length());
  154. }
  155. });
  156. dataChannelMap.emplace(id, dc);
  157. this_thread::sleep_for(1s);
  158. }
  159. cout << "Cleaning up..." << endl;
  160. dataChannelMap.clear();
  161. peerConnectionMap.clear();
  162. delete params;
  163. return 0;
  164. }
  165. // Create and setup a PeerConnection
  166. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  167. weak_ptr<WebSocket> wws, string id) {
  168. auto pc = make_shared<PeerConnection>(config);
  169. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  170. pc->onGatheringStateChange(
  171. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  172. pc->onLocalDescription([wws, id](Description description) {
  173. json message = {
  174. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  175. if (auto ws = wws.lock())
  176. ws->send(message.dump());
  177. });
  178. pc->onLocalCandidate([wws, id](Candidate candidate) {
  179. json message = {{"id", id},
  180. {"type", "candidate"},
  181. {"candidate", string(candidate)},
  182. {"mid", candidate.mid()}};
  183. if (auto ws = wws.lock())
  184. ws->send(message.dump());
  185. });
  186. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  187. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  188. << endl;
  189. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  190. dc->onMessage([id, wdc = make_weak_ptr(dc)](const variant<binary, string> &message) {
  191. static bool firstMessage = true;
  192. if (holds_alternative<string>(message) && (!echoDataChannelMessages || firstMessage)) {
  193. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  194. firstMessage = false;
  195. } else if (echoDataChannelMessages) {
  196. bool echoed = false;
  197. if (auto dc = wdc.lock()) {
  198. dc->send(message);
  199. echoed = true;
  200. }
  201. confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
  202. get<string>(message).length());
  203. }
  204. });
  205. dc->send("Hello from " + localId);
  206. dataChannelMap.emplace(id, dc);
  207. });
  208. peerConnectionMap.emplace(id, pc);
  209. return pc;
  210. };
  211. void confirmOnStdout(bool echoed, string id, string type, size_t length) {
  212. static long count = 0;
  213. static long freq = 100;
  214. if (!(++count%freq)) {
  215. cout << "Received " << count << " pings in total from host " << id << ", most recent of type "
  216. << type << " and " << (echoed ? "" : "un") << "successfully echoed most recent ping of size "
  217. << length << " back to " << id << endl;
  218. if (count >= (freq * 10) && freq < 1000000) {
  219. freq *= 10;
  220. }
  221. }
  222. }
  223. // Helper function to generate a random ID
  224. string randomId(size_t length) {
  225. static const string characters(
  226. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  227. string id(length, '0');
  228. default_random_engine rng(random_device{}());
  229. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  230. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  231. return id;
  232. }