main.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public License
  11. * as published by the Free Software Foundation; either version 2
  12. * of the License, or (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. #include "rtc/rtc.hpp"
  23. #include <nlohmann/json.hpp>
  24. #include <algorithm>
  25. #include <iostream>
  26. #include <memory>
  27. #include <random>
  28. #include <thread>
  29. #include <unordered_map>
  30. using namespace rtc;
  31. using namespace std;
  32. using namespace std::chrono_literals;
  33. using json = nlohmann::json;
  34. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  35. unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
  36. unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
  37. string localId;
  38. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  39. weak_ptr<WebSocket> wws, string id);
  40. string randomId(size_t length);
  41. int main(int argc, char **argv) {
  42. rtc::InitLogger(LogLevel::Warning);
  43. Configuration config;
  44. config.iceServers.emplace_back("stun:stun.l.google.com:19302"); // change to your STUN server
  45. localId = randomId(8);
  46. cout << "The local ID is: " << localId << endl;
  47. auto ws = make_shared<WebSocket>();
  48. ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
  49. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  50. ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
  51. ws->onMessage([&](const variant<binary, string> &data) {
  52. if (!holds_alternative<string>(data))
  53. return;
  54. json message = json::parse(get<string>(data));
  55. auto it = message.find("id");
  56. if (it == message.end())
  57. return;
  58. string id = it->get<string>();
  59. it = message.find("type");
  60. if (it == message.end())
  61. return;
  62. string type = it->get<string>();
  63. shared_ptr<PeerConnection> pc;
  64. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  65. pc = jt->second;
  66. } else if (type == "offer") {
  67. cout << "Answering to " + id << endl;
  68. pc = createPeerConnection(config, ws, id);
  69. } else {
  70. return;
  71. }
  72. if (type == "offer" || type == "answer") {
  73. auto sdp = message["description"].get<string>();
  74. pc->setRemoteDescription(Description(sdp, type));
  75. } else if (type == "candidate") {
  76. auto sdp = message["candidate"].get<string>();
  77. auto mid = message["mid"].get<string>();
  78. pc->addRemoteCandidate(Candidate(sdp, mid));
  79. }
  80. });
  81. const string url = "ws://localhost:8000/" + localId;
  82. ws->open(url);
  83. cout << "Waiting for signaling to be connected..." << endl;
  84. while (!ws->isOpen()) {
  85. if (ws->isClosed())
  86. return 1;
  87. this_thread::sleep_for(100ms);
  88. }
  89. while (true) {
  90. string id;
  91. cout << "Enter a remote ID to send an offer:" << endl;
  92. cin >> id;
  93. cin.ignore();
  94. if (id.empty())
  95. break;
  96. if (id == localId)
  97. continue;
  98. cout << "Offering to " + id << endl;
  99. auto pc = createPeerConnection(config, ws, id);
  100. // We are the offerer, so create a data channel to initiate the process
  101. const string label = "test";
  102. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  103. auto dc = pc->createDataChannel(label);
  104. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  105. cout << "DataChannel from " << id << " open" << endl;
  106. if (auto dc = wdc.lock())
  107. dc->send("Hello from " + localId);
  108. });
  109. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  110. dc->onMessage([id](const variant<binary, string> &message) {
  111. if (!holds_alternative<string>(message))
  112. return;
  113. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  114. });
  115. dataChannelMap.emplace(id, dc);
  116. this_thread::sleep_for(1s);
  117. }
  118. cout << "Cleaning up..." << endl;
  119. dataChannelMap.clear();
  120. peerConnectionMap.clear();
  121. return 0;
  122. }
  123. // Create and setup a PeerConnection
  124. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  125. weak_ptr<WebSocket> wws, string id) {
  126. auto pc = make_shared<PeerConnection>(config);
  127. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  128. pc->onGatheringStateChange(
  129. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  130. pc->onLocalDescription([wws, id](const Description &description) {
  131. json message = {
  132. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  133. if (auto ws = wws.lock())
  134. ws->send(message.dump());
  135. });
  136. pc->onLocalCandidate([wws, id](const Candidate &candidate) {
  137. json message = {{"id", id},
  138. {"type", "candidate"},
  139. {"candidate", string(candidate)},
  140. {"mid", candidate.mid()}};
  141. if (auto ws = wws.lock())
  142. ws->send(message.dump());
  143. });
  144. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  145. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  146. << endl;
  147. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  148. dc->onMessage([id](const variant<binary, string> &message) {
  149. if (!holds_alternative<string>(message))
  150. return;
  151. cout << "Message from " << id << " received: " << get<string>(message) << endl;
  152. });
  153. dc->send("Hello from " + localId);
  154. dataChannelMap.emplace(id, dc);
  155. });
  156. peerConnectionMap.emplace(id, pc);
  157. return pc;
  158. };
  159. // Helper function to generate a random ID
  160. string randomId(size_t length) {
  161. static const string characters(
  162. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  163. string id(length, '0');
  164. default_random_engine rng(random_device{}());
  165. uniform_int_distribution<int> dist(0, characters.size() - 1);
  166. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  167. return id;
  168. }