main.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. auto params = std::make_unique<Cmdline>(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. localId = randomId(4);
  62. cout << "The local ID is: " << localId << endl;
  63. auto ws = make_shared<WebSocket>();
  64. std::promise<void> wsPromise;
  65. auto wsFuture = wsPromise.get_future();
  66. ws->onOpen([&wsPromise]() {
  67. cout << "WebSocket connected, signaling ready" << endl;
  68. wsPromise.set_value();
  69. });
  70. ws->onError([&wsPromise](string s) {
  71. cout << "WebSocket error" << endl;
  72. wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
  73. });
  74. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  75. ws->onMessage([&](variant<binary, string> data) {
  76. if (!holds_alternative<string>(data))
  77. return;
  78. json message = json::parse(get<string>(data));
  79. auto it = message.find("id");
  80. if (it == message.end())
  81. return;
  82. string id = it->get<string>();
  83. it = message.find("type");
  84. if (it == message.end())
  85. return;
  86. string type = it->get<string>();
  87. shared_ptr<PeerConnection> pc;
  88. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  89. pc = jt->second;
  90. } else if (type == "offer") {
  91. cout << "Answering to " + id << endl;
  92. pc = createPeerConnection(config, ws, id);
  93. } else {
  94. return;
  95. }
  96. if (type == "offer" || type == "answer") {
  97. auto sdp = message["description"].get<string>();
  98. pc->setRemoteDescription(Description(sdp, type));
  99. } else if (type == "candidate") {
  100. auto sdp = message["candidate"].get<string>();
  101. auto mid = message["mid"].get<string>();
  102. pc->addRemoteCandidate(Candidate(sdp, mid));
  103. }
  104. });
  105. string wsPrefix = "";
  106. if (params->webSocketServer().substr(0, 5).compare("ws://") != 0) {
  107. wsPrefix = "ws://";
  108. }
  109. const string url = wsPrefix + params->webSocketServer() + ":" +
  110. to_string(params->webSocketPort()) + "/" + localId;
  111. cout << "Url is " << url << endl;
  112. ws->open(url);
  113. cout << "Waiting for signaling to be connected..." << endl;
  114. wsFuture.get();
  115. while (true) {
  116. string id;
  117. cout << "Enter a remote ID to send an offer:" << endl;
  118. cin >> id;
  119. cin.ignore();
  120. if (id.empty())
  121. break;
  122. if (id == localId)
  123. continue;
  124. cout << "Offering to " + id << endl;
  125. auto pc = createPeerConnection(config, ws, id);
  126. // We are the offerer, so create a data channel to initiate the process
  127. const string label = "test";
  128. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  129. auto dc = pc->createDataChannel(label);
  130. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  131. cout << "DataChannel from " << id << " open" << endl;
  132. if (auto dc = wdc.lock())
  133. dc->send("Hello from " + localId);
  134. });
  135. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  136. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  137. if (holds_alternative<string>(data))
  138. cout << "Message from " << id << " received: " << get<string>(data) << endl;
  139. else
  140. cout << "Binary message from " << id
  141. << " received, size=" << get<binary>(data).size() << endl;
  142. });
  143. dataChannelMap.emplace(id, dc);
  144. }
  145. cout << "Cleaning up..." << 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<PeerConnection> createPeerConnection(const Configuration &config,
  157. weak_ptr<WebSocket> wws, string id) {
  158. auto pc = make_shared<PeerConnection>(config);
  159. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  160. pc->onGatheringStateChange(
  161. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  162. pc->onLocalDescription([wws, id](Description description) {
  163. json message = {
  164. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  165. if (auto ws = wws.lock())
  166. ws->send(message.dump());
  167. });
  168. pc->onLocalCandidate([wws, id](Candidate candidate) {
  169. json message = {{"id", id},
  170. {"type", "candidate"},
  171. {"candidate", string(candidate)},
  172. {"mid", candidate.mid()}};
  173. if (auto ws = wws.lock())
  174. ws->send(message.dump());
  175. });
  176. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  177. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  178. << endl;
  179. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  180. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  181. if (holds_alternative<string>(data))
  182. cout << "Message from " << id << " received: " << get<string>(data) << endl;
  183. else
  184. cout << "Binary message from " << id
  185. << " received, size=" << get<binary>(data).size() << endl;
  186. });
  187. dc->send("Hello from " + localId);
  188. dataChannelMap.emplace(id, dc);
  189. });
  190. peerConnectionMap.emplace(id, pc);
  191. return pc;
  192. };
  193. // Helper function to generate a random ID
  194. string randomId(size_t length) {
  195. static const string characters(
  196. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  197. string id(length, '0');
  198. default_random_engine rng(random_device{}());
  199. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  200. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  201. return id;
  202. }