Qt TCP Socket reading issue - c++

I try to read the TCP port with Qt libraries and a GUI Program.
The problem is that when I use this code to read the socket:
QTcpSocket *a = new QTcpSocket();
a->connectToHost("127.0.0.1", 5000);
a->read(data,LEN);
it's not working and I need to put an extra function:
a->waitForReadyRead(1)
but this functions slows my Program, I use a pthread to run this code continuously. I have a question, how can I speed up my program and also to read the data successfully?

You need to use Qt event loop and connect 'data available' event signal in order to read socket data asynchronously. Connection syntax in your case may look like this:
QObject::connect(s, &QTcpSocket::readyRead, yourReaderFunction);
Your program loop should contain a call to event processing function QApplication::processEvents(), or you can use built-in loop QApplication::exec().
The signals and slots mechanism is a core feature of Qt, and you need to understand and use it properly in order to interact with most of Qt classes:
Signal and slot basics
Qt5 new signal and slot syntax

Related

How to use ASIO along with QT4?

I have written a C++ 11 code using asio to send/receive the packets from network. To work with asio, asio::io_service::run() need to be called and the main thread will be waiting in this function.
Now, in one of the applications, I need to develop a Gui for which I need to use Qt 4.8. But for a Qt Gui application, the main thread need to wait in QApplication::exec(). Though Qt has its own libraries to send/receive data from Network, I would like to use the code with asio.
How can I use asio along with Qt?
Without seeing your code.. a high-level generic approach:
Call io_context::run() in a new thread. All async handlers will execute in this thread.
Use a mutex to ensure the data model can be safely shared between ASIO and the GUI. Lock the mutex consistently any time the data is read or updated.
Use Qt signals and slots and/or condition_variable to signal the GUI from ASIO completion handlers whenever the UI needs to be updated. Do not touch the GUI directly from ASIO code, as only the UI thread may update the UI.

Connect multiple clients using single thread with synchronous or asynchronous?

a few months ago,i had asked some relative questions about qt tcp network programming for my project. And finally the software came out. But after learned more detail about qt event mechans and signals -slots realization. I have some worry about my program performance and stability.
The key problem is that server using a single thread for handle multiple tcpsockets. the brief introduction code for realization:
incomingConnection function is writen as following: two QSignalMapper are used for map each socket SlotReadyRead and SlotDisconnected
void ServerModule::incomingConnection(qintptr socketDescriptor)
{
m_tcpSocket = new QTcpSocket(this);
if (!m_tcpSocket->setSocketDescriptor(socketDescriptor)) {
return;
}
connect(m_tcpSocket, SIGNAL(readyRead()), m_readyReadSignalMapper, SLOT(map()));
m_readyReadSignalMapper->setMapping(m_tcpSocket, m_tcpSocket);
connect(m_tcpSocket, SIGNAL(disconnected()), m_disconnectedSignalMapper, SLOT(map()));
m_disconnectedSignalMapper->setMapping(m_tcpSocket, m_tcpSocket);
}
the sever construct function:
ServerModule::ServerModule(QObject * parent) : QTcpServer(parent),m_readyReadSignalMapper(new QSignalMapper(this)),m_disconnectedSignalMapper(new QSignalMapper(this))
{
connect(m_readyReadSignalMapper, SIGNAL(mapped(QObject *)), this, SLOT(SlotReadyRead(QObject *)));
connect(m_disconnectedSignalMapper, SIGNAL(mapped(QObject *)), this, SLOT(SlotDisconnected(QObject*)));
......other code
}
SlotReadyRead and SlotDisconnected functions are every normal,it convertsQObject* socketObject to QTcpSocket *socket and then do some work.
So i have learned that if write like aboving connect function with specific connect mode
Qt::DirectConnection
Qt::QueuedConnection
Qt::BlockingQueuedConnection
if using single thread,only first mode and second mode can be used . And use first mode, it's synchronous ,if second, it's asynchronous. My program default using first mode, so the signals -slots are connected synchronous.
So here is my worry:
1. How about the single thread performance for handling multiple sockets?can it reach 500 connection /per second concurrency?what's the max connected can be handled?
2. if at the same time,multiple sockets are ready to read then called qt core to send readyRead signals, the QSignalMapper can handle it properly?
3. should I connect socket and QSignalMapper using QueuedConnection mode, because this connecting is not connected immediately, it's using event queue and postEvent to connect. so its asynchronous. Is in this situation,the concurrency request can be handled?
First a few issues with your code:
QSignalMapper just adds complexity to your code
Don't use a member variable for QTcpSocket, you will be overwriting it every time and chances are that you might use an invalid pointer
If you are not doing something complex or using QSslSocket don't subclass QTcpServer, just connect to the newConnection() signal and call nextPendingConnection()
Now to the connect part of your questioning you should read https://woboq.com/blog/how-qt-signals-slots-work.html in short:
Qt::DirectConnection - means once the signal is emitted the slot will called immediately, if the object that has the slot lives in another thread it will be called in the caller thread. This is used if Qt::AutoConnection is used and both objects live in the same thread.
Qt::QueuedConnection - means that when the signal is emitted it will create an event and be put on the event loop to be dispatched once you return to the event loop, this is useful for different threads as the slot will called on the thread that the object lives in. This is NOT what you want here, nor how QTcpSocket should be used (read the docs).
Qt::BlockingQueuedConnection - is very rare to use this one, this like the above puts the event on the event loop of the other thread, but it blocks until the slot was called.
The only "Sync" method is the blocking one, because it would block, but that doesn't mean it's a problem, you can have a non-gui thread that blocks waiting for the reply of the gui thread while asking the user for a password for example.
To the questions now:
UPDATED 1 and 3 for more clarification
Performance really depends on what these sockets will do, how long each will take to process the request and send a reply, in Cutelyst Web Framework a single thread on an i5 can process up to 100K req/s (returning a 'Hello Wolrd!' string HTTP response), the maximum number depends of concurrent connections will be limited by max ports available, memory available to allocate memory and of course if it's CPU intensive the clients will have a long time waiting.
The most common way is to call sender() on your slot, due a small hit on performance (due sender() call) it's faster to use a lambda:
void Parser::readyRead() {
auto socket = qobject_cast<QTcpSocket*>(sender());
...
}
Or with a lambda:
connect(sock, &QTcpSocket::readyRead, [sock] () {
// use sock obj here
});
Again QSignalMapper is not what you want, you should call sender() to get the QTcpSocket or use a lambda capturing the socket object (this is a little faster)
No shouldn't used QueuedConnection connection on your QSignalMapper, because that will cause an unneeded overhead due the fact that it will put the event on the event loop queue and it will be processed later, it might also cause weird bugs due the way QTcpSockets handle data (you must consume all the bytesAvailable() on readyReady since if no extra data arrives readyRead() signal is not emitted again.

Why does writing to this socket discard the read buffer (and is that really what's happening)?

Consider the following snippet:
QTcpServer server;
server.listen(QHostAddress::LocalHost);
QTcpSocket clientSocket;
clientSocket.connectToHost(server.serverAddress(), server.serverPort());
// ...wait for connection to succeed...
QTcpSocket *serverSocket = server.nextPendingConnection();
serverSocket->write("test");
serverSocket->close();
The goal of this snippet is to create two connected sockets by creating a QTcpServer that listens for incoming connections and connecting to it with another QTcpSocket. Once the connection is established, data is written to one of the sockets and it is closed.
QAbstractSocket::close() invokes disconnectFromHost() The documentation for QAbstractSocket::disconnectFromHost() clearly states that:
If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written.
The next snippet enters the event loop briefly to process pending events and then attempts to read the string from the other socket:
QCoreApplication::processEvents();
qDebug() << clientSocket.readAll();
This prints "test" and all is well. Or perhaps not. If I modify the previous snippet by prepending a call to write(), the data can no longer be read from the socket:
clientSocket.write("test");
QCoreApplication::processEvents();
qDebug() << clientSocket.readAll();
This prints an empty string ("") instead of the expected value from the previous run. Why can't the socket read the value this time?
Note: this only manifests itself on the Windows platform. Neither Linux nor Mac OS X builds of Qt exhibit this behavior, instead printing the expected value in both cases.
Second note: if you want to play with the code, there's a working Gist here: https://gist.github.com/nathan-osman/ee6116d120903db84384
Third note: here's a screenshot of a Wireshark capture of the TCP exchange:
Im not very familiar with Qt, but on Windows, there is no Fork. You are trying to fit to parallel tasks on the same thread, but you should have the client running on a different thread than the server.
You're writing asynchronous code in synchronous style in a way that doesn't ensure that you wait long enough for things to happen. Calling processEvents simply means "do any work that is currently available to do" not "do work and/or wait for work until no more work can possibly arrive". You treat it like the latter, but it means the former.
The simplest fix is not to do that.
Connect slots or functors to relevant socket signals, and return control to the event loop. Never use waitForXxx functions, they simply aren't specified sufficiently to allow use in all cases. Never mind the horrible reentrancy issues you'll face when reentering the event loop.
If there's no event loop in the thread where your code runs, spin up your own:
QEventLoop loop;
...
connect(serverSocket, &QAbstractSocket::disconnected,
&loop, &QEventLoop::quit);
loop.exec(); // this will keep executing until the socked is disconnected

C++ Threading Pattern for Qt serial port

My aim is to receive messages from a serial device without blocking the main thread (GUI) and to try to separate the platform-dependent logic (GUI and serial port) from the business logic (processing the messages) for ease of porting to other platforms
Context: I'm using Qt, and the QtSerialPort module. The message protocol is simple, 0xff is used to end each message.
I've found 4 solutions so far:
Method 1:
Using one thread to read a serial port and fill a buffer
Using another thread to read the buffer, extract valid messages (into another buffer? not sure how this will work yet)
Using yet another thread to parse the messages
Method 2:
Using one thread to read a serial port, and extract valid messages into a buffer
Using another thread to parse the messages
Method 3:
Using one thread to read a serial port, extract a valid message, and block till that message is processed, making use of QtSerialPort's internal read buffer to buffer incoming data
Method 4:
Using the main thread to asynchronously read serial port, extract a valid message, and for each message, spawn a new thread to process them
Methods 1,2 and 3 differ by the number of threads the general workload is split up into, though I don't know which is best.
I'm currently using method 4, which is horribly inefficient and doesn't work well on lower-end computers, due to the enormous number of threads being spawned, and every time I move or interact with the GUI, serial communication halts. Spawning a thread for each message also makes the order of the messages non-deterministic, which hasn't been a major problem so far...
Are there other methods, what are the pros (if any) and cons of each, and which is the best to use? Thanks!
EDIT: A problem with processing messages in the main thread is that interacting with GUI (even moving the window) would block the message processing function. Is there any way around this?
I think there are two main advantages that you can obtain by using multithreading:
Avoiding poor GUI performance due to the GUI-handling routines being held off by the serial port processing routine
(perhaps more important) Avoid loss of serial data caused by buffer overflow when the GUI routines hold off the serial-data-reading routine for too long.
You should only need to spawn a single thread. Just have that thread read data from the serial port as it comes in (by connecting the QSerialPort's readyRead() signal to a slot that calls read() on the QSerialPort object), and then emit a signal (with a QByteArray argument) whenever it wants to send some serial data to the GUI. Your main/GUI thread can receive the data via a QueuedConnection that will not block either the serial-thread or the main/GUI thread.
That's pretty much all there is to it; the only other thing to worry about is a clean shutdown. Be sure to have another cross-thread signal/slot connection to the QThread's quit() slot, so that when it's time to quit, you can emit that signal and then call wait() on the QThread to wait for it to respond by going away. Once wait() has returned you can safely delete the QThread object.
You can avoid additional threads at all by simply relying on Qt event loop (so far the main thread, the one also handling the GUI to be clear, will be blocked only when a message is actually received by the serial port).
Otherwise if you want to completely handle serial port in a dedicated thread, then the solution is to implement a class deriving from QThread and then override the run() function with something like this:
void MyClass::run()
{
QSerialPort port;
// ... serial port initialization here
// Connect signals/slots
connect(&port, SIGNAL(readyRead()), this, SLOT(readData()));
port.open();
// Start a new message loop on this thread
exec();
}
Where readData is a function implemented in MyClass for handling the received data. Since port is owned by the new thread (being created in run()) then its events will be handled by the thread itself (in a completely independent manner with respect to the main thread).
If you want at some point communicate something to the main thread (e.g.: you received something on serial which should cause a change in your GUI) then you can still use Qt's signals/slots. Simply implement a signal on MyClass and implement a slot on an object handled by the main thread (e.g.: your main form): then simply connect the signal for MyClass and the slot on your main form and you're done: signals/slots is THE solution for cross-thread communication in Qt.
You could also avoid using any (additional) threads and take advantage of Qt event loop. Read about events, QioDevice; then Qt would pass your device file descriptor to its multiplexing loop (e.g. to poll(2)....); probably QSocketNotifier should work (on Posix) on a non-socket file descriptor like a serial device.
Details are probably OS specific

How to interrupt select/pselect running in QThread

I have a QThread that reads from a socket and sends a signal (QT signal) when there are any data available.
This would be easy with blocking read(2), but i need to be able to stop the thread from outside without waiting for too long.
If I were using pthread I would use pselect and pthread_kill(thread_id, some_signal), but QThread doesn't
seem to have any similar methods. And adding a dependcy on pthread to this project doesn't seem to elegant.
I also don't want to use the other ugly methods like constantly trying to read from the socket with some relatively small timeout.
Edit: The sockets are not TCP, but bluetooth L2CAP.
A not too elegant, but simple and working solution:
Create a pipe and let select wait for either the pipe or my socket. This way I can stop the wait anytime by writing something to the pipe.
Instead of dealing with the threading yourself you can use the asynchronous interface of QTcpSocket. Check out the Fortune Client example.
You can send a signal to the terminate() slot of your QThread. This will stop your thread according to OS scheduling policies.