main.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 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. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  43. weak_ptr<WebSocket> wws, string id);
  44. string randomId(size_t length);
  45. int main(int argc, char **argv) try {
  46. Cmdline params(argc, argv);
  47. rtc::InitLogger(LogLevel::Info);
  48. Configuration config;
  49. string stunServer = "";
  50. if (params.noStun()) {
  51. cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
  52. << endl;
  53. } else {
  54. if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
  55. stunServer = "stun:";
  56. }
  57. stunServer += params.stunServer() + ":" + to_string(params.stunPort());
  58. cout << "Stun server is " << stunServer << endl;
  59. config.iceServers.emplace_back(stunServer);
  60. }
  61. if (params.udpMux()) {
  62. cout << "ICE UDP mux enabled" << endl;
  63. config.enableIceUdpMux = true;
  64. }
  65. localId = randomId(4);
  66. cout << "The local ID is: " << localId << 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)](variant<binary, string> data) {
  141. if (holds_alternative<string>(data))
  142. cout << "Message from " << id << " received: " << get<string>(data) << endl;
  143. else
  144. cout << "Binary message from " << id
  145. << " received, size=" << get<binary>(data).size() << endl;
  146. });
  147. dataChannelMap.emplace(id, dc);
  148. }
  149. cout << "Cleaning up..." << endl;
  150. dataChannelMap.clear();
  151. peerConnectionMap.clear();
  152. return 0;
  153. } catch (const std::exception &e) {
  154. std::cout << "Error: " << e.what() << std::endl;
  155. dataChannelMap.clear();
  156. peerConnectionMap.clear();
  157. return -1;
  158. }
  159. // Create and setup a PeerConnection
  160. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  161. weak_ptr<WebSocket> wws, string id) {
  162. auto pc = make_shared<PeerConnection>(config);
  163. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  164. pc->onGatheringStateChange(
  165. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  166. pc->onLocalDescription([wws, id](Description description) {
  167. json message = {
  168. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  169. if (auto ws = wws.lock())
  170. ws->send(message.dump());
  171. });
  172. pc->onLocalCandidate([wws, id](Candidate candidate) {
  173. json message = {{"id", id},
  174. {"type", "candidate"},
  175. {"candidate", string(candidate)},
  176. {"mid", candidate.mid()}};
  177. if (auto ws = wws.lock())
  178. ws->send(message.dump());
  179. });
  180. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  181. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  182. << endl;
  183. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  184. if (auto dc = wdc.lock())
  185. dc->send("Hello from " + localId);
  186. });
  187. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  188. dc->onMessage([id](variant<binary, string> data) {
  189. if (holds_alternative<string>(data))
  190. cout << "Message from " << id << " received: " << get<string>(data) << endl;
  191. else
  192. cout << "Binary message from " << id
  193. << " received, size=" << get<binary>(data).size() << endl;
  194. });
  195. dataChannelMap.emplace(id, dc);
  196. });
  197. peerConnectionMap.emplace(id, pc);
  198. return pc;
  199. };
  200. // Helper function to generate a random ID
  201. string randomId(size_t length) {
  202. static const string characters(
  203. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  204. string id(length, '0');
  205. default_random_engine rng(random_device{}());
  206. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  207. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  208. return id;
  209. }