def send_message(self, message, callback=None): """ Attempt to send a message to the previously running instance of the application. Returns True if the message is sent successfully, or False otherwise. Alternatively, if a callback is provided the function will return immediately and the boolean will be sent to the callback instead. """ message = json.dumps(message) if sys.version_info.major == 3: packedLen = struct.pack("!I", len(message)).decode() else: packedLen = struct.pack("!I", len(message)) message = packedLen + message # Create a socket. sock = QLocalSocket(self) # Build our helper functions. def error(err): """ Return False to the callback. """ callback(False) def connected(): """ Send our message. """ sock.writeData(message, len(message)) def bytesWritten(bytes): """ If we've written everything, close and return True. """ if not sock.bytesToWrite(): sock.close() callback(True) if callback: sock.error.connect(error) sock.connect.connect(connected) sock.bytesWritten.connect(bytesWritten) # Now connect. sock.connectToServer(self._app_id) if not callback: # Do things synchronously. connected = sock.waitForConnected(5000) if not connected: return False # Write it. sock.writeData(message, len(message)) # Wait until we've written everything. while sock.bytesToWrite(): success = sock.waitForBytesWritten(5000) if not success: sock.close() return False sock.close() return True