2
0

turn_connectivity.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #include "rtc/rtc.hpp"
  9. #include <atomic>
  10. #include <chrono>
  11. #include <iostream>
  12. #include <memory>
  13. #include <thread>
  14. using namespace rtc;
  15. using namespace std;
  16. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  17. void test_turn_connectivity() {
  18. InitLogger(LogLevel::Debug);
  19. Configuration config1;
  20. config1.iceTransportPolicy = TransportPolicy::Relay; // force relay
  21. // TURN server example (use your own server in production)
  22. config1.iceServers.emplace_back(
  23. "turn:openrelayproject:[email protected]:80");
  24. PeerConnection pc1(config1);
  25. Configuration config2;
  26. // STUN server example (use your own server in production)
  27. config2.iceServers.emplace_back("stun:openrelay.metered.ca:80");
  28. PeerConnection pc2(config2);
  29. pc1.onStateChange([](PeerConnection::State state) { cout << "State 1: " << state << endl; });
  30. pc1.onIceStateChange(
  31. [](PeerConnection::IceState state) { cout << "ICE state 1: " << state << endl; });
  32. pc1.onGatheringStateChange([&pc1, &pc2](PeerConnection::GatheringState state) {
  33. cout << "Gathering state 1: " << state << endl;
  34. if (state == PeerConnection::GatheringState::Complete) {
  35. auto sdp = pc1.localDescription().value();
  36. cout << "Description 1: " << sdp << endl;
  37. pc2.setRemoteDescription(string(sdp));
  38. }
  39. });
  40. pc1.onSignalingStateChange([](PeerConnection::SignalingState state) {
  41. cout << "Signaling state 1: " << state << endl;
  42. });
  43. pc2.onLocalDescription([&pc1](Description sdp) {
  44. cout << "Description 2: " << sdp << endl;
  45. pc1.setRemoteDescription(string(sdp));
  46. });
  47. pc2.onLocalCandidate([&pc1](Candidate candidate) {
  48. // Filter server reflexive candidates
  49. if (candidate.type() != rtc::Candidate::Type::ServerReflexive)
  50. return;
  51. cout << "Candidate 2: " << candidate << endl;
  52. pc1.addRemoteCandidate(string(candidate));
  53. });
  54. pc2.onStateChange([](PeerConnection::State state) { cout << "State 2: " << state << endl; });
  55. pc2.onIceStateChange(
  56. [](PeerConnection::IceState state) { cout << "ICE state 2: " << state << endl; });
  57. pc2.onGatheringStateChange([](PeerConnection::GatheringState state) {
  58. cout << "Gathering state 2: " << state << endl;
  59. });
  60. pc2.onSignalingStateChange([](PeerConnection::SignalingState state) {
  61. cout << "Signaling state 2: " << state << endl;
  62. });
  63. shared_ptr<DataChannel> dc2;
  64. pc2.onDataChannel([&dc2](shared_ptr<DataChannel> dc) {
  65. cout << "DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
  66. if (dc->label() != "test") {
  67. cerr << "Wrong DataChannel label" << endl;
  68. return;
  69. }
  70. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  71. if (auto dc = wdc.lock()) {
  72. cout << "DataChannel 2: Open" << endl;
  73. dc->send("Hello from 2");
  74. }
  75. });
  76. dc->onMessage([](variant<binary, string> message) {
  77. if (holds_alternative<string>(message)) {
  78. cout << "Message 2: " << get<string>(message) << endl;
  79. }
  80. });
  81. std::atomic_store(&dc2, dc);
  82. });
  83. auto dc1 = pc1.createDataChannel("test");
  84. dc1->onOpen([wdc1 = make_weak_ptr(dc1)]() {
  85. auto dc1 = wdc1.lock();
  86. if (!dc1)
  87. return;
  88. cout << "DataChannel 1: Open" << endl;
  89. dc1->send("Hello from 1");
  90. });
  91. dc1->onClosed([]() { cout << "DataChannel 1: Closed" << endl; });
  92. dc1->onMessage([](const variant<binary, string> &message) {
  93. if (holds_alternative<string>(message)) {
  94. cout << "Message 1: " << get<string>(message) << endl;
  95. }
  96. });
  97. // Wait a bit
  98. int attempts = 10;
  99. shared_ptr<DataChannel> adc2;
  100. while ((!(adc2 = std::atomic_load(&dc2)) || !adc2->isOpen() || !dc1->isOpen()) && attempts--)
  101. this_thread::sleep_for(1s);
  102. if (pc1.state() != PeerConnection::State::Connected ||
  103. pc2.state() != PeerConnection::State::Connected)
  104. throw runtime_error("PeerConnection is not connected");
  105. if ((pc1.iceState() != PeerConnection::IceState::Connected &&
  106. pc1.iceState() != PeerConnection::IceState::Completed) ||
  107. (pc2.iceState() != PeerConnection::IceState::Connected &&
  108. pc2.iceState() != PeerConnection::IceState::Completed))
  109. throw runtime_error("ICE is not connected");
  110. if (!adc2 || !adc2->isOpen() || !dc1->isOpen())
  111. throw runtime_error("DataChannel is not open");
  112. if (auto addr = pc1.localAddress())
  113. cout << "Local address 1: " << *addr << endl;
  114. if (auto addr = pc1.remoteAddress())
  115. cout << "Remote address 1: " << *addr << endl;
  116. if (auto addr = pc2.localAddress())
  117. cout << "Local address 2: " << *addr << endl;
  118. if (auto addr = pc2.remoteAddress())
  119. cout << "Remote address 2: " << *addr << endl;
  120. Candidate local, remote;
  121. if (!pc1.getSelectedCandidatePair(&local, &remote))
  122. throw runtime_error("getSelectedCandidatePair failed");
  123. cout << "Local candidate 1: " << local << endl;
  124. cout << "Remote candidate 1: " << remote << endl;
  125. if (local.type() != Candidate::Type::Relayed)
  126. throw runtime_error("Connection is not relayed as expected");
  127. // Try to open a second data channel with another label
  128. shared_ptr<DataChannel> second2;
  129. pc2.onDataChannel([&second2](shared_ptr<DataChannel> dc) {
  130. cout << "Second DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
  131. if (dc->label() != "second") {
  132. cerr << "Wrong second DataChannel label" << endl;
  133. return;
  134. }
  135. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  136. if (auto dc = wdc.lock())
  137. dc->send("Second hello from 2");
  138. });
  139. dc->onMessage([](variant<binary, string> message) {
  140. if (holds_alternative<string>(message)) {
  141. cout << "Second Message 2: " << get<string>(message) << endl;
  142. }
  143. });
  144. std::atomic_store(&second2, dc);
  145. });
  146. auto second1 = pc1.createDataChannel("second");
  147. second1->onOpen([wsecond1 = make_weak_ptr(second1)]() {
  148. auto second1 = wsecond1.lock();
  149. if (!second1)
  150. return;
  151. cout << "Second DataChannel 1: Open" << endl;
  152. second1->send("Second hello from 1");
  153. });
  154. second1->onClosed([]() { cout << "Second DataChannel 1: Closed" << endl; });
  155. second1->onMessage([](const variant<binary, string> &message) {
  156. if (holds_alternative<string>(message)) {
  157. cout << "Second Message 1: " << get<string>(message) << endl;
  158. }
  159. });
  160. // Wait a bit
  161. attempts = 10;
  162. shared_ptr<DataChannel> asecond2;
  163. while (
  164. (!(asecond2 = std::atomic_load(&second2)) || !asecond2->isOpen() || !second1->isOpen()) &&
  165. attempts--)
  166. this_thread::sleep_for(1s);
  167. if (!asecond2 || !asecond2->isOpen() || !second1->isOpen())
  168. throw runtime_error("Second DataChannel is not open");
  169. // Try to open a negotiated channel
  170. DataChannelInit init;
  171. init.negotiated = true;
  172. init.id = 42;
  173. auto negotiated1 = pc1.createDataChannel("negotiated", init);
  174. auto negotiated2 = pc2.createDataChannel("negoctated", init);
  175. if (!negotiated1->isOpen() || !negotiated2->isOpen())
  176. throw runtime_error("Negotiated DataChannel is not open");
  177. std::atomic<bool> received = false;
  178. negotiated2->onMessage([&received](const variant<binary, string> &message) {
  179. if (holds_alternative<string>(message)) {
  180. cout << "Second Message 2: " << get<string>(message) << endl;
  181. received = true;
  182. }
  183. });
  184. negotiated1->send("Hello from negotiated channel");
  185. // Wait a bit
  186. attempts = 5;
  187. while (!received && attempts--)
  188. this_thread::sleep_for(1s);
  189. if (!received)
  190. throw runtime_error("Negotiated DataChannel failed");
  191. // Delay close of peer 2 to check closing works properly
  192. pc1.close();
  193. this_thread::sleep_for(1s);
  194. pc2.close();
  195. this_thread::sleep_for(1s);
  196. cout << "Success" << endl;
  197. }