Does Qt have a QIODevice
pair that would work for intra-process point-to-point communications?
One could use the concrete QTCPSocket
or QLocalSocket
, but the server-side connection API is a bit cumbersome, and it seems wasteful to force the data through the OS.
The following is a usable, rudimentary implementation. It uses an internal signal-slot pair to push the data to the other endpoint. That way either end of the connection can live in any thread, and the ends can be moved between threads without losing data or inducing any races.
The private
QRingBuffer
is used in lieu of reinventing the wheel. AddQT += core-private
to the.pro
file to make that available. Qt PIMPL is used to gain access to the internal device buffers in Qt versions 5.7 and above.If you wish to instantiate an open pipe, as may often be the case, you can pass the I/O mode to the constructor. Typical use:
Whatever you write to one pipe, ends up as readable data in the other, connected pipes, and vice versa. In the above example, data written to
end1
is readable from bothend2
andend3
independently. Data written toend2
is readable fromend1
.end3
is effectively a listen-only pipe. Connection of additional pipes is cheap - there's no O(N) cost associated with sending big chunks of data to multiple pipes, because readQRingBuffer
s of connected pipes store shallow copies of entire byte arrays sent from the originating pipe.All of the
QIODevice
semantics hold - you can connect to thereadyRead
signal, use the pipe with aQDataStream
or aQTextStream
, etc. As with anyQIODevice
, you can only use the class from itsthread()
, but the other endpoint can live in any thread, and both can be moved between threads as desired, without loss of data.If the other pipe end is not open and readable, the writes are no-ops, even though they succeed. Closing the pipe clears the read and write buffers, so that it can be re-opened for reuse.
The pipe buffers write data by default, and the write buffer can be forcibly flushed using
AppPipe::flush()
, unless opened inQIODevice::Unbuffered
mode.The
hasIncoming
andhasOutgoing
signals are useful in monitoring the data going over the pipe.A minimal test harness: