main.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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) try {
  46. auto params = std::make_unique<Cmdline>(argc, argv);
  47. rtc::InitLogger(LogLevel::Debug);
  48. Configuration config;
  49. string stunServer = "";
  50. if (params->noStun()) {
  51. cout << "No stun server is configured. Only local hosts and public IP addresses suported." << endl;
  52. } else {
  53. if (params->stunServer().substr(0,5).compare("stun:") != 0) {
  54. stunServer = "stun:";
  55. }
  56. stunServer += params->stunServer() + ":" + to_string(params->stunPort());
  57. cout << "Stun server is " << stunServer << endl;
  58. config.iceServers.emplace_back(stunServer);
  59. }
  60. localId = randomId(4);
  61. cout << "The local ID is: " << localId << endl;
  62. echoDataChannelMessages = params->echoDataChannelMessages();
  63. cout << "Received data channel messages will be "
  64. << (echoDataChannelMessages ? "echoed back to sender" : "printed to stdout") << endl;
  65. auto ws = make_shared<WebSocket>();
  66. ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
  67. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  68. ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
  69. ws->onMessage([&](variant<binary, string> data) {
  70. if (!holds_alternative<string>(data))
  71. return;
  72. json message = json::parse(get<string>(data));
  73. auto it = message.find("id");
  74. if (it == message.end())
  75. return;
  76. string id = it->get<string>();
  77. it = message.find("type");
  78. if (it == message.end())
  79. return;
  80. string type = it->get<string>();
  81. shared_ptr<PeerConnection> pc;
  82. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  83. pc = jt->second;
  84. } else if (type == "offer") {
  85. cout << "Answering to " + id << endl;
  86. pc = createPeerConnection(config, ws, id);
  87. } else {
  88. return;
  89. }
  90. if (type == "offer" || type == "answer") {
  91. auto sdp = message["description"].get<string>();
  92. pc->setRemoteDescription(Description(sdp, type));
  93. } else if (type == "candidate") {
  94. auto sdp = message["candidate"].get<string>();
  95. auto mid = message["mid"].get<string>();
  96. pc->addRemoteCandidate(Candidate(sdp, mid));
  97. }
  98. });
  99. string wsPrefix = "";
  100. if (params->webSocketServer().substr(0,5).compare("ws://") != 0) {
  101. wsPrefix = "ws://";
  102. }
  103. const string url = wsPrefix + params->webSocketServer() + ":" +
  104. to_string(params->webSocketPort()) + "/" + localId;
  105. cout << "Url is " << url << endl;
  106. ws->open(url);
  107. cout << "Waiting for signaling to be connected..." << endl;
  108. while (!ws->isOpen()) {
  109. if (ws->isClosed())
  110. return 1;
  111. this_thread::sleep_for(100ms);
  112. }
  113. while (true) {
  114. string id;
  115. cout << "Enter a remote ID to send an offer:" << endl;
  116. cin >> id;
  117. cin.ignore();
  118. if (id.empty())
  119. break;
  120. if (id == localId)
  121. continue;
  122. cout << "Offering to " + id << endl;
  123. auto pc = createPeerConnection(config, ws, id);
  124. // We are the offerer, so create a data channel to initiate the process
  125. const string label = "test";
  126. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  127. auto dc = pc->createDataChannel(label);
  128. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  129. cout << "DataChannel from " << id << " open" << endl;
  130. if (auto dc = wdc.lock())
  131. dc->send("Hello from " + localId);
  132. });
  133. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  134. dc->onMessage([id, wdc = make_weak_ptr(dc)](const variant<binary, string> &message) {
  135. static bool firstMessage = true;
  136. if (holds_alternative<string>(message) && (!echoDataChannelMessages || firstMessage)) {
  137. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  138. firstMessage = false;
  139. } else if (echoDataChannelMessages) {
  140. bool echoed = false;
  141. if (auto dc = wdc.lock()) {
  142. dc->send(message);
  143. echoed = true;
  144. }
  145. confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
  146. get<string>(message).length());
  147. }
  148. });
  149. dataChannelMap.emplace(id, dc);
  150. }
  151. cout << "Cleaning up..." << endl;
  152. dataChannelMap.clear();
  153. peerConnectionMap.clear();
  154. return 0;
  155. } catch (const std::exception &e) {
  156. std::cout << "Error: " << e.what() << std::endl;
  157. dataChannelMap.clear();
  158. peerConnectionMap.clear();
  159. return -1;
  160. }
  161. // Create and setup a PeerConnection
  162. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  163. weak_ptr<WebSocket> wws, string id) {
  164. auto pc = make_shared<PeerConnection>(config);
  165. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  166. pc->onGatheringStateChange(
  167. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  168. pc->onLocalDescription([wws, id](Description description) {
  169. json message = {
  170. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  171. if (auto ws = wws.lock())
  172. ws->send(message.dump());
  173. });
  174. pc->onLocalCandidate([wws, id](Candidate candidate) {
  175. json message = {{"id", id},
  176. {"type", "candidate"},
  177. {"candidate", string(candidate)},
  178. {"mid", candidate.mid()}};
  179. if (auto ws = wws.lock())
  180. ws->send(message.dump());
  181. });
  182. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  183. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  184. << endl;
  185. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  186. dc->onMessage([id, wdc = make_weak_ptr(dc)](const variant<binary, string> &message) {
  187. static bool firstMessage = true;
  188. if (holds_alternative<string>(message) && (!echoDataChannelMessages || firstMessage)) {
  189. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  190. firstMessage = false;
  191. } else if (echoDataChannelMessages) {
  192. bool echoed = false;
  193. if (auto dc = wdc.lock()) {
  194. dc->send(message);
  195. echoed = true;
  196. }
  197. confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
  198. get<string>(message).length());
  199. }
  200. });
  201. dc->send("Hello from " + localId);
  202. dataChannelMap.emplace(id, dc);
  203. });
  204. peerConnectionMap.emplace(id, pc);
  205. return pc;
  206. };
  207. void confirmOnStdout(bool echoed, string id, string type, size_t length) {
  208. static long count = 0;
  209. static long freq = 100;
  210. if (!(++count%freq)) {
  211. cout << "Received " << count << " pings in total from host " << id << ", most recent of type "
  212. << type << " and " << (echoed ? "" : "un") << "successfully echoed most recent ping of size "
  213. << length << " back to " << id << endl;
  214. if (count >= (freq * 10) && freq < 1000000) {
  215. freq *= 10;
  216. }
  217. }
  218. }
  219. // Helper function to generate a random ID
  220. string randomId(size_t length) {
  221. static const string characters(
  222. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  223. string id(length, '0');
  224. default_random_engine rng(random_device{}());
  225. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  226. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  227. return id;
  228. }