main.cpp 8.8 KB

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