juce_NetworkServiceDiscovery.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #if JUCE_ANDROID
  20. extern void acquireMulticastLock();
  21. extern void releaseMulticastLock();
  22. #endif
  23. NetworkServiceDiscovery::Advertiser::Advertiser (const String& serviceTypeUID,
  24. const String& serviceDescription,
  25. int broadcastPortToUse, int connectionPort,
  26. RelativeTime minTimeBetweenBroadcasts)
  27. : Thread ("Discovery_broadcast"),
  28. message (serviceTypeUID), broadcastPort (broadcastPortToUse),
  29. minInterval (minTimeBetweenBroadcasts)
  30. {
  31. message.setAttribute ("id", Uuid().toString());
  32. message.setAttribute ("name", serviceDescription);
  33. message.setAttribute ("address", String());
  34. message.setAttribute ("port", connectionPort);
  35. startThread (2);
  36. }
  37. NetworkServiceDiscovery::Advertiser::~Advertiser()
  38. {
  39. stopThread (2000);
  40. socket.shutdown();
  41. }
  42. void NetworkServiceDiscovery::Advertiser::run()
  43. {
  44. if (! socket.bindToPort (0))
  45. {
  46. jassertfalse;
  47. return;
  48. }
  49. while (! threadShouldExit())
  50. {
  51. sendBroadcast();
  52. wait ((int) minInterval.inMilliseconds());
  53. }
  54. }
  55. void NetworkServiceDiscovery::Advertiser::sendBroadcast()
  56. {
  57. auto localAddress = IPAddress::getLocalAddress();
  58. message.setAttribute ("address", localAddress.toString());
  59. auto broadcastAddress = IPAddress::getInterfaceBroadcastAddress (localAddress);
  60. auto data = message.toString (XmlElement::TextFormat().singleLine().withoutHeader());
  61. socket.write (broadcastAddress.toString(), broadcastPort, data.toRawUTF8(), (int) data.getNumBytesAsUTF8());
  62. }
  63. //==============================================================================
  64. NetworkServiceDiscovery::AvailableServiceList::AvailableServiceList (const String& serviceType, int broadcastPort)
  65. : Thread ("Discovery_listen"), serviceTypeUID (serviceType)
  66. {
  67. #if JUCE_ANDROID
  68. acquireMulticastLock();
  69. #endif
  70. socket.bindToPort (broadcastPort);
  71. startThread (2);
  72. }
  73. NetworkServiceDiscovery::AvailableServiceList::~AvailableServiceList()
  74. {
  75. socket.shutdown();
  76. stopThread (2000);
  77. #if JUCE_ANDROID
  78. releaseMulticastLock();
  79. #endif
  80. }
  81. void NetworkServiceDiscovery::AvailableServiceList::run()
  82. {
  83. while (! threadShouldExit())
  84. {
  85. if (socket.waitUntilReady (true, 200) == 1)
  86. {
  87. char buffer[1024];
  88. auto bytesRead = socket.read (buffer, sizeof (buffer) - 1, false);
  89. if (bytesRead > 10)
  90. if (auto xml = parseXML (String (CharPointer_UTF8 (buffer),
  91. CharPointer_UTF8 (buffer + bytesRead))))
  92. if (xml->hasTagName (serviceTypeUID))
  93. handleMessage (*xml);
  94. }
  95. removeTimedOutServices();
  96. }
  97. }
  98. std::vector<NetworkServiceDiscovery::Service> NetworkServiceDiscovery::AvailableServiceList::getServices() const
  99. {
  100. const ScopedLock sl (listLock);
  101. auto listCopy = services;
  102. return listCopy;
  103. }
  104. void NetworkServiceDiscovery::AvailableServiceList::handleAsyncUpdate()
  105. {
  106. if (onChange != nullptr)
  107. onChange();
  108. }
  109. void NetworkServiceDiscovery::AvailableServiceList::handleMessage (const XmlElement& xml)
  110. {
  111. Service service;
  112. service.instanceID = xml.getStringAttribute ("id");
  113. if (service.instanceID.trim().isNotEmpty())
  114. {
  115. service.description = xml.getStringAttribute ("name");
  116. service.address = IPAddress (xml.getStringAttribute ("address"));
  117. service.port = xml.getIntAttribute ("port");
  118. service.lastSeen = Time::getCurrentTime();
  119. handleMessage (service);
  120. }
  121. }
  122. static void sortServiceList (std::vector<NetworkServiceDiscovery::Service>& services)
  123. {
  124. auto compareServices = [] (const NetworkServiceDiscovery::Service& s1,
  125. const NetworkServiceDiscovery::Service& s2)
  126. {
  127. return s1.instanceID < s2.instanceID;
  128. };
  129. std::sort (services.begin(), services.end(), compareServices);
  130. }
  131. void NetworkServiceDiscovery::AvailableServiceList::handleMessage (const Service& service)
  132. {
  133. const ScopedLock sl (listLock);
  134. for (auto& s : services)
  135. {
  136. if (s.instanceID == service.instanceID)
  137. {
  138. if (s.description != service.description
  139. || s.address != service.address
  140. || s.port != service.port)
  141. {
  142. s = service;
  143. triggerAsyncUpdate();
  144. }
  145. s.lastSeen = service.lastSeen;
  146. return;
  147. }
  148. }
  149. services.push_back (service);
  150. sortServiceList (services);
  151. triggerAsyncUpdate();
  152. }
  153. void NetworkServiceDiscovery::AvailableServiceList::removeTimedOutServices()
  154. {
  155. const double timeoutSeconds = 5.0;
  156. auto oldestAllowedTime = Time::getCurrentTime() - RelativeTime::seconds (timeoutSeconds);
  157. const ScopedLock sl (listLock);
  158. auto oldEnd = std::end (services);
  159. auto newEnd = std::remove_if (std::begin (services), oldEnd,
  160. [=] (const Service& s) { return s.lastSeen < oldestAllowedTime; });
  161. if (newEnd != oldEnd)
  162. {
  163. services.erase (newEnd, oldEnd);
  164. triggerAsyncUpdate();
  165. }
  166. }
  167. } // namespace juce