juce_InterprocessConnection.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. class InterprocessConnectionServer;
  20. class MemoryBlock;
  21. //==============================================================================
  22. /**
  23. Manages a simple two-way messaging connection to another process, using either
  24. a socket or a named pipe as the transport medium.
  25. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  26. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27. and incoming messages will result in a callback via the messageReceived()
  28. method.
  29. To open a pipe and wait for another client to connect to it, use the createPipe()
  30. method.
  31. To act as a socket server and create connections for one or more client, see the
  32. InterprocessConnectionServer class.
  33. @see InterprocessConnectionServer, Socket, NamedPipe
  34. @tags{Events}
  35. */
  36. class JUCE_API InterprocessConnection
  37. {
  38. public:
  39. //==============================================================================
  40. /** Creates a connection.
  41. Connections are created manually, connecting them with the connectToSocket()
  42. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  43. when a client wants to connect.
  44. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  45. connectionLost() and messageReceived() methods will
  46. always be made using the message thread; if false,
  47. these will be called immediately on the connection's
  48. own thread.
  49. @param magicMessageHeaderNumber a magic number to use in the header to check the
  50. validity of the data blocks being sent and received. This
  51. can be any number, but the sender and receiver must obviously
  52. use matching values or they won't recognise each other.
  53. */
  54. InterprocessConnection (bool callbacksOnMessageThread = true,
  55. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  56. /** Destructor. */
  57. virtual ~InterprocessConnection();
  58. //==============================================================================
  59. /** Tries to connect this object to a socket.
  60. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  61. object waiting to receive client connections on this port number.
  62. @param hostName the host computer, either a network address or name
  63. @param portNumber the socket port number to try to connect to
  64. @param timeOutMillisecs how long to keep trying before giving up
  65. @returns true if the connection is established successfully
  66. @see Socket
  67. */
  68. bool connectToSocket (const String& hostName,
  69. int portNumber,
  70. int timeOutMillisecs);
  71. /** Tries to connect the object to an existing named pipe.
  72. For this to work, another process on the same computer must already have opened
  73. an InterprocessConnection object and used createPipe() to create a pipe for this
  74. to connect to.
  75. @param pipeName the name to use for the pipe - this should be unique to your app
  76. @param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
  77. to the pipe, or -1 for an infinite timeout.
  78. @returns true if it connects successfully.
  79. @see createPipe, NamedPipe
  80. */
  81. bool connectToPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs);
  82. /** Tries to create a new pipe for other processes to connect to.
  83. This creates a pipe with the given name, so that other processes can use
  84. connectToPipe() to connect to the other end.
  85. @param pipeName the name to use for the pipe - this should be unique to your app
  86. @param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
  87. to the pipe, or -1 for an infinite timeout
  88. @param mustNotExist if set to true, the method will fail if the pipe already exists
  89. @returns true if the pipe was created, or false if it fails (e.g. if another process is
  90. already using the pipe)
  91. */
  92. bool createPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs, bool mustNotExist = false);
  93. /** Disconnects and closes any currently-open sockets or pipes. */
  94. void disconnect();
  95. /** True if a socket or pipe is currently active. */
  96. bool isConnected() const;
  97. /** Returns the socket that this connection is using (or nullptr if it uses a pipe). */
  98. StreamingSocket* getSocket() const noexcept { return socket.get(); }
  99. /** Returns the pipe that this connection is using (or nullptr if it uses a socket). */
  100. NamedPipe* getPipe() const noexcept { return pipe.get(); }
  101. /** Returns the name of the machine at the other end of this connection.
  102. This may return an empty string if the name is unknown.
  103. */
  104. String getConnectedHostName() const;
  105. //==============================================================================
  106. /** Tries to send a message to the other end of this connection.
  107. This will fail if it's not connected, or if there's some kind of write error. If
  108. it succeeds, the connection object at the other end will receive the message by
  109. a callback to its messageReceived() method.
  110. @see messageReceived
  111. */
  112. bool sendMessage (const MemoryBlock& message);
  113. //==============================================================================
  114. /** Called when the connection is first connected.
  115. If the connection was created with the callbacksOnMessageThread flag set, then
  116. this will be called on the message thread; otherwise it will be called on a server
  117. thread.
  118. */
  119. virtual void connectionMade() = 0;
  120. /** Called when the connection is broken.
  121. If the connection was created with the callbacksOnMessageThread flag set, then
  122. this will be called on the message thread; otherwise it will be called on a server
  123. thread.
  124. */
  125. virtual void connectionLost() = 0;
  126. /** Called when a message arrives.
  127. When the object at the other end of this connection sends us a message with sendMessage(),
  128. this callback is used to deliver it to us.
  129. If the connection was created with the callbacksOnMessageThread flag set, then
  130. this will be called on the message thread; otherwise it will be called on a server
  131. thread.
  132. @see sendMessage
  133. */
  134. virtual void messageReceived (const MemoryBlock& message) = 0;
  135. private:
  136. //==============================================================================
  137. CriticalSection pipeAndSocketLock;
  138. std::unique_ptr<StreamingSocket> socket;
  139. std::unique_ptr<NamedPipe> pipe;
  140. bool callbackConnectionState = false;
  141. const bool useMessageThread;
  142. const uint32 magicMessageHeader;
  143. int pipeReceiveMessageTimeout = -1;
  144. friend class InterprocessConnectionServer;
  145. void initialiseWithSocket (StreamingSocket*);
  146. void initialiseWithPipe (NamedPipe*);
  147. void deletePipeAndSocket();
  148. void connectionMadeInt();
  149. void connectionLostInt();
  150. void deliverDataInt (const MemoryBlock&);
  151. bool readNextMessage();
  152. int readData (void*, int);
  153. struct ConnectionThread;
  154. std::unique_ptr<ConnectionThread> thread;
  155. std::atomic<bool> threadIsRunning { false };
  156. void runThread();
  157. int writeData (void*, int);
  158. JUCE_DECLARE_WEAK_REFERENCEABLE (InterprocessConnection)
  159. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection)
  160. };
  161. } // namespace juce