main.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 Source Code Form is subject to the terms of the Mozilla Public
  11. * License, v. 2.0. If a copy of the MPL was not distributed with this
  12. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  13. */
  14. #include "rtc/rtc.hpp"
  15. #include "parse_cl.h"
  16. #include <nlohmann/json.hpp>
  17. #include <algorithm>
  18. #include <chrono>
  19. #include <future>
  20. #include <iostream>
  21. #include <memory>
  22. #include <random>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <unordered_map>
  26. using namespace std::chrono_literals;
  27. using std::shared_ptr;
  28. using std::weak_ptr;
  29. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  30. using nlohmann::json;
  31. std::string localId;
  32. std::unordered_map<std::string, shared_ptr<rtc::PeerConnection>> peerConnectionMap;
  33. std::unordered_map<std::string, shared_ptr<rtc::DataChannel>> dataChannelMap;
  34. shared_ptr<rtc::PeerConnection> createPeerConnection(const rtc::Configuration &config,
  35. weak_ptr<rtc::WebSocket> wws, std::string id);
  36. std::string randomId(size_t length);
  37. int main(int argc, char **argv) try {
  38. Cmdline params(argc, argv);
  39. rtc::InitLogger(rtc::LogLevel::Info);
  40. rtc::Configuration config;
  41. std::string stunServer = "";
  42. if (params.noStun()) {
  43. std::cout
  44. << "No STUN server is configured. Only local hosts and public IP addresses supported."
  45. << std::endl;
  46. } else {
  47. if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
  48. stunServer = "stun:";
  49. }
  50. stunServer += params.stunServer() + ":" + std::to_string(params.stunPort());
  51. std::cout << "STUN server is " << stunServer << std::endl;
  52. config.iceServers.emplace_back(stunServer);
  53. }
  54. if (params.udpMux()) {
  55. std::cout << "ICE UDP mux enabled" << std::endl;
  56. config.enableIceUdpMux = true;
  57. }
  58. localId = randomId(4);
  59. std::cout << "The local ID is " << localId << std::endl;
  60. auto ws = std::make_shared<rtc::WebSocket>();
  61. std::promise<void> wsPromise;
  62. auto wsFuture = wsPromise.get_future();
  63. ws->onOpen([&wsPromise]() {
  64. std::cout << "WebSocket connected, signaling ready" << std::endl;
  65. wsPromise.set_value();
  66. });
  67. ws->onError([&wsPromise](std::string s) {
  68. std::cout << "WebSocket error" << std::endl;
  69. wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
  70. });
  71. ws->onClosed([]() { std::cout << "WebSocket closed" << std::endl; });
  72. ws->onMessage([&config, wws = make_weak_ptr(ws)](auto data) {
  73. // data holds either std::string or rtc::binary
  74. if (!std::holds_alternative<std::string>(data))
  75. return;
  76. json message = json::parse(std::get<std::string>(data));
  77. auto it = message.find("id");
  78. if (it == message.end())
  79. return;
  80. auto id = it->get<std::string>();
  81. it = message.find("type");
  82. if (it == message.end())
  83. return;
  84. auto type = it->get<std::string>();
  85. shared_ptr<rtc::PeerConnection> pc;
  86. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  87. pc = jt->second;
  88. } else if (type == "offer") {
  89. std::cout << "Answering to " + id << std::endl;
  90. pc = createPeerConnection(config, wws, id);
  91. } else {
  92. return;
  93. }
  94. if (type == "offer" || type == "answer") {
  95. auto sdp = message["description"].get<std::string>();
  96. pc->setRemoteDescription(rtc::Description(sdp, type));
  97. } else if (type == "candidate") {
  98. auto sdp = message["candidate"].get<std::string>();
  99. auto mid = message["mid"].get<std::string>();
  100. pc->addRemoteCandidate(rtc::Candidate(sdp, mid));
  101. }
  102. });
  103. const std::string wsPrefix =
  104. params.webSocketServer().find("://") == std::string::npos ? "ws://" : "";
  105. const std::string url = wsPrefix + params.webSocketServer() + ":" +
  106. std::to_string(params.webSocketPort()) + "/" + localId;
  107. std::cout << "WebSocket URL is " << url << std::endl;
  108. ws->open(url);
  109. std::cout << "Waiting for signaling to be connected..." << std::endl;
  110. wsFuture.get();
  111. while (true) {
  112. std::string id;
  113. std::cout << "Enter a remote ID to send an offer:" << std::endl;
  114. std::cin >> id;
  115. std::cin.ignore();
  116. if (id.empty())
  117. break;
  118. if (id == localId) {
  119. std::cout << "Invalid remote ID (This is the local ID)" << std::endl;
  120. continue;
  121. }
  122. std::cout << "Offering to " + id << std::endl;
  123. auto pc = createPeerConnection(config, ws, id);
  124. // We are the offerer, so create a data channel to initiate the process
  125. const std::string label = "test";
  126. std::cout << "Creating DataChannel with label \"" << label << "\"" << std::endl;
  127. auto dc = pc->createDataChannel(label);
  128. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  129. std::cout << "DataChannel from " << id << " open" << std::endl;
  130. if (auto dc = wdc.lock())
  131. dc->send("Hello from " + localId);
  132. });
  133. dc->onClosed([id]() { std::cout << "DataChannel from " << id << " closed" << std::endl; });
  134. dc->onMessage([id, wdc = make_weak_ptr(dc)](auto data) {
  135. // data holds either std::string or rtc::binary
  136. if (std::holds_alternative<std::string>(data))
  137. std::cout << "Message from " << id << " received: " << std::get<std::string>(data)
  138. << std::endl;
  139. else
  140. std::cout << "Binary message from " << id
  141. << " received, size=" << std::get<rtc::binary>(data).size() << std::endl;
  142. });
  143. dataChannelMap.emplace(id, dc);
  144. }
  145. std::cout << "Cleaning up..." << std::endl;
  146. dataChannelMap.clear();
  147. peerConnectionMap.clear();
  148. return 0;
  149. } catch (const std::exception &e) {
  150. std::cout << "Error: " << e.what() << std::endl;
  151. dataChannelMap.clear();
  152. peerConnectionMap.clear();
  153. return -1;
  154. }
  155. // Create and setup a PeerConnection
  156. shared_ptr<rtc::PeerConnection> createPeerConnection(const rtc::Configuration &config,
  157. weak_ptr<rtc::WebSocket> wws, std::string id) {
  158. auto pc = std::make_shared<rtc::PeerConnection>(config);
  159. pc->onStateChange(
  160. [](rtc::PeerConnection::State state) { std::cout << "State: " << state << std::endl; });
  161. pc->onGatheringStateChange([](rtc::PeerConnection::GatheringState state) {
  162. std::cout << "Gathering State: " << state << std::endl;
  163. });
  164. pc->onLocalDescription([wws, id](rtc::Description description) {
  165. json message = {{"id", id},
  166. {"type", description.typeString()},
  167. {"description", std::string(description)}};
  168. if (auto ws = wws.lock())
  169. ws->send(message.dump());
  170. });
  171. pc->onLocalCandidate([wws, id](rtc::Candidate candidate) {
  172. json message = {{"id", id},
  173. {"type", "candidate"},
  174. {"candidate", std::string(candidate)},
  175. {"mid", candidate.mid()}};
  176. if (auto ws = wws.lock())
  177. ws->send(message.dump());
  178. });
  179. pc->onDataChannel([id](shared_ptr<rtc::DataChannel> dc) {
  180. std::cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  181. << std::endl;
  182. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  183. if (auto dc = wdc.lock())
  184. dc->send("Hello from " + localId);
  185. });
  186. dc->onClosed([id]() { std::cout << "DataChannel from " << id << " closed" << std::endl; });
  187. dc->onMessage([id](auto data) {
  188. // data holds either std::string or rtc::binary
  189. if (std::holds_alternative<std::string>(data))
  190. std::cout << "Message from " << id << " received: " << std::get<std::string>(data)
  191. << std::endl;
  192. else
  193. std::cout << "Binary message from " << id
  194. << " received, size=" << std::get<rtc::binary>(data).size() << std::endl;
  195. });
  196. dataChannelMap.emplace(id, dc);
  197. });
  198. peerConnectionMap.emplace(id, pc);
  199. return pc;
  200. };
  201. // Helper function to generate a random ID
  202. std::string randomId(size_t length) {
  203. using std::chrono::high_resolution_clock;
  204. static thread_local std::mt19937 rng(
  205. static_cast<unsigned int>(high_resolution_clock::now().time_since_epoch().count()));
  206. static const std::string characters(
  207. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  208. std::string id(length, '0');
  209. std::uniform_int_distribution<int> uniform(0, int(characters.size() - 1));
  210. std::generate(id.begin(), id.end(), [&]() { return characters.at(uniform(rng)); });
  211. return id;
  212. }