The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

214 lines
9.4KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. #pragma once
  24. class InterprocessConnectionServer;
  25. class MemoryBlock;
  26. //==============================================================================
  27. /**
  28. Manages a simple two-way messaging connection to another process, using either
  29. a socket or a named pipe as the transport medium.
  30. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  32. and incoming messages will result in a callback via the messageReceived()
  33. method.
  34. To open a pipe and wait for another client to connect to it, use the createPipe()
  35. method.
  36. To act as a socket server and create connections for one or more client, see the
  37. InterprocessConnectionServer class.
  38. @see InterprocessConnectionServer, Socket, NamedPipe
  39. */
  40. class JUCE_API InterprocessConnection
  41. {
  42. public:
  43. //==============================================================================
  44. /** Creates a connection.
  45. Connections are created manually, connecting them with the connectToSocket()
  46. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  47. when a client wants to connect.
  48. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  49. connectionLost() and messageReceived() methods will
  50. always be made using the message thread; if false,
  51. these will be called immediately on the connection's
  52. own thread.
  53. @param magicMessageHeaderNumber a magic number to use in the header to check the
  54. validity of the data blocks being sent and received. This
  55. can be any number, but the sender and receiver must obviously
  56. use matching values or they won't recognise each other.
  57. */
  58. InterprocessConnection (bool callbacksOnMessageThread = true,
  59. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  60. /** Destructor. */
  61. virtual ~InterprocessConnection();
  62. //==============================================================================
  63. /** Tries to connect this object to a socket.
  64. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  65. object waiting to receive client connections on this port number.
  66. @param hostName the host computer, either a network address or name
  67. @param portNumber the socket port number to try to connect to
  68. @param timeOutMillisecs how long to keep trying before giving up
  69. @returns true if the connection is established successfully
  70. @see Socket
  71. */
  72. bool connectToSocket (const String& hostName,
  73. int portNumber,
  74. int timeOutMillisecs);
  75. /** Tries to connect the object to an existing named pipe.
  76. For this to work, another process on the same computer must already have opened
  77. an InterprocessConnection object and used createPipe() to create a pipe for this
  78. to connect to.
  79. @param pipeName the name to use for the pipe - this should be unique to your app
  80. @param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
  81. to the pipe, or -1 for an infinite timeout.
  82. @returns true if it connects successfully.
  83. @see createPipe, NamedPipe
  84. */
  85. bool connectToPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs);
  86. /** Tries to create a new pipe for other processes to connect to.
  87. This creates a pipe with the given name, so that other processes can use
  88. connectToPipe() to connect to the other end.
  89. @param pipeName the name to use for the pipe - this should be unique to your app
  90. @param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
  91. to the pipe, or -1 for an infinite timeout
  92. @param mustNotExist if set to true, the method will fail if the pipe already exists
  93. @returns true if the pipe was created, or false if it fails (e.g. if another process is
  94. already using using the pipe)
  95. */
  96. bool createPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs, bool mustNotExist = false);
  97. /** Disconnects and closes any currently-open sockets or pipes. */
  98. void disconnect();
  99. /** True if a socket or pipe is currently active. */
  100. bool isConnected() const;
  101. /** Returns the socket that this connection is using (or nullptr if it uses a pipe). */
  102. StreamingSocket* getSocket() const noexcept { return socket; }
  103. /** Returns the pipe that this connection is using (or nullptr if it uses a socket). */
  104. NamedPipe* getPipe() const noexcept { return pipe; }
  105. /** Returns the name of the machine at the other end of this connection.
  106. This may return an empty string if the name is unknown.
  107. */
  108. String getConnectedHostName() const;
  109. //==============================================================================
  110. /** Tries to send a message to the other end of this connection.
  111. This will fail if it's not connected, or if there's some kind of write error. If
  112. it succeeds, the connection object at the other end will receive the message by
  113. a callback to its messageReceived() method.
  114. @see messageReceived
  115. */
  116. bool sendMessage (const MemoryBlock& message);
  117. //==============================================================================
  118. /** Called when the connection is first connected.
  119. If the connection was created with the callbacksOnMessageThread flag set, then
  120. this will be called on the message thread; otherwise it will be called on a server
  121. thread.
  122. */
  123. virtual void connectionMade() = 0;
  124. /** Called when the connection is broken.
  125. If the connection was created with the callbacksOnMessageThread flag set, then
  126. this will be called on the message thread; otherwise it will be called on a server
  127. thread.
  128. */
  129. virtual void connectionLost() = 0;
  130. /** Called when a message arrives.
  131. When the object at the other end of this connection sends us a message with sendMessage(),
  132. this callback is used to deliver it to us.
  133. If the connection was created with the callbacksOnMessageThread flag set, then
  134. this will be called on the message thread; otherwise it will be called on a server
  135. thread.
  136. @see sendMessage
  137. */
  138. virtual void messageReceived (const MemoryBlock& message) = 0;
  139. private:
  140. //==============================================================================
  141. WeakReference<InterprocessConnection>::Master masterReference;
  142. friend class WeakReference<InterprocessConnection>;
  143. CriticalSection pipeAndSocketLock;
  144. ScopedPointer<StreamingSocket> socket;
  145. ScopedPointer<NamedPipe> pipe;
  146. bool callbackConnectionState;
  147. const bool useMessageThread;
  148. const uint32 magicMessageHeader;
  149. int pipeReceiveMessageTimeout;
  150. friend class InterprocessConnectionServer;
  151. void initialiseWithSocket (StreamingSocket*);
  152. void initialiseWithPipe (NamedPipe*);
  153. void deletePipeAndSocket();
  154. void connectionMadeInt();
  155. void connectionLostInt();
  156. void deliverDataInt (const MemoryBlock&);
  157. bool readNextMessageInt();
  158. struct ConnectionThread;
  159. friend struct ConnectionThread;
  160. friend struct ContainerDeletePolicy<ConnectionThread>;
  161. ScopedPointer<ConnectionThread> thread;
  162. void runThread();
  163. int writeData (void*, int);
  164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection)
  165. };