main.cpp 8.4 KB

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