main.cpp 8.6 KB

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