QUdpSocket HeartBeat behaviour - qt

I need to send the status of my Qt application through and Upd socket every seconds. How can I achive this? Should I subclass QThread e using QThread::sleep or is there a best approch ? thanks

In the end I use a different approch:
a QTimer:
QTimer iAmAliveTimer.setInterval(1500);
iAmAliveTimer.setSingleShot(true);
connect(&iAmAliveTimer, SIGNAL(timeout()), this, SLOT(sendIamAlive()), Qt::UniqueConnection);
iAmAliveTimer.start();
when the SLOT is called, I send what I need through my socket.

Related

How to set QWebSocketServer disconnect time while not use for a long time?

I'm using QWebSocketServer and QWebChannel for communicating between c++ and js.
No correspondence for about 30 minutes,the socket will be cloesd. There is a report,"CRITICAL, WebSocket is already in CLOSING or CLOSED state".
How can I set the time to 2 hours or more?
You shoud use QTimer object.
In files:
.h
QTimer m_timeToDisconnect;//(better to be private)
.cpp
m_timeToDisconnect.setSingleShot(true);
m_timeToDisconnect.setTimerType(Qt::VeryCoarseTimer);
connect(m_pTcpSocket, &QTcpSocket::readyRead, this, &MySocket::getMessage);
connect(m_timeToDisconnect, &QTimer::timeout, [=](){m_pTcpSocket->close();});
when you get some data &QTcpSocket::readyRead, you should start Again Timer
m_timeToDisconnect.start(7200000)

How to send data to a specific client on a multithreaded server

I am trying to build a multithreaded server. The problem that I am encountering is that the emitted signal sends message to all clients instead to the specific one on a specific thread.
I tried to solve the issue by creating a QList of threads, but how do I connect them specifically?? When signal is emitted, it wakes up all my threads, the problem is getting worse by each connection, since the clients are dynamically allocated as they are connecting.
Code:
void NetworkServer::incomingConnection(qintptr socketDescriptor)
{
QThread *thread = new QThread;
threadhandle *session = new threadhandle;
QObject::connect(this, &NetworkServer::stopped, session, &threadhandle::close);
QObject::connect(this, &NetworkServer::stopped, thread, &threadhandle::quit);
QObject::connect(session, &threadhandle::closed, thread, &threadhandle::quit);
QObject::connect(thread, &QThread::started, this, &NetworkServer::threadStarted, Qt::DirectConnection);
QObject::connect(thread, &QThread::finished, this, &NetworkServer::threadFinished, Qt::DirectConnection);
QObject::connect(thread, &QThread::finished, session, &QObject::deleteLater);
QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater);
//the problem is here, I can send message to all clients connected, but how to specifiy a thread/client???
QObject::connect(this, &NetworkServer::sendMsgToThread, session, &threadhandle::sendMsgToClient);
thread->start();
session->moveToThread(thread);
QMetaObject::invokeMethod(session, "open", Qt::QueuedConnection, Q_ARG(qintptr, socketDescriptor));
Update - 40 minutes later - Problem solved
I apologize for not providing more details, basically I am building a simple client-server relationship. Message is send from server GUI line in text format to a specific client.
After some thinking I came up with a solution.
so for each new thread, we will append its session to: QList<threadhandle*>sessionList
After that we are going to edit the sendMsgToClient()
// user clicks on Send Message button in GUI
void NetworkServer::sendMsgToClient(int clientNum, QString msg)
{
//connect the signal to a specific thread, clientNum is selected from a table in mainWindow GUI where the NetworkServer class is initiated
QObject::connect(this, &NetworkServer::sendMsgToThread, sessionList.at(clientNum), &threadhandle::sendMsgToClient);
//emit the signal to specific thread
emit sendMsgToThread(clientNum, msg);
//disconnect the signal, since it is no longer needed
QObject::disconnect(this, &NetworkServer::sendMsgToThread, sessionList.at(clientNum), &threadhandle::sendMsgToClient);
}
Hard to say really without MRE that builds and presents your exact problem. But, guessing from context: no clue how NetworkServer::sendMsgToThread or threadhandle::sendMsgToClient are implemented, but I guess you could store the thread ID/index/any other identifier and then pass it to specific thread only, possible via some proxy object?
Point is, sendMsgToThread gets connected to multiple slots, which is probably not what you want; instead those single session-thread pairs need to be somehow distinguished, e.g. by thread ID/its index in list, whatever.
I guess you could wrap the session and thread in some other class, that would be stored (and referred to) by the server by some of the aforementioned IDs, and it would forward the messages to the worker (session) object. But I cannot really tell without at least basic knowledge of your code's architecture.

How to wait for a mousePressEvent (C++)

I my Qt application written in C++, I would like to wait for a mousePressEvent to do something after the mouse pressed.
Would you please hehp?
Thanks in advance.
Kind regards.
You can use the signal/slots to connect your mouseEvent to a specific slot.
Or you can create a QEventLoop and quit it by emitting "mSignalTriggert" when a mouseEvent happend.
QEventLoop l;
connect(this, &MainWindow::mSignalTriggerd, &l, &QEventLoop::quit);
l.exec();

Is there a way trigger a signal from another signal in Qt?

I already have an application in place and am tweaking it now. In this regard, I am introducing a new signal, which has to be emitted when another signal is emitted. Is this possible in Qt?
Writing a slot just to emit this signal feels so primitive and lame...
Detailing further, I have to connect the button signalClicked() to my own signal say sendSignal(enumtype)...
EDIT: Forgot to mention that I need to send a data with the second signal.
Yes, it is possible without creating additional slot. Just connect signal to signal:
connect(this,SIGNAL(someSignal()),this,SIGNAL(anotherSignal()));
More information in doc.
Edit:
You can share data in connection as usual. Dirty example:
QWidget* obj = new QWidget;
obj->setWindowTitle("WindowTitle");
//share data, pass wrong data to the signal
QObject::connect(obj,SIGNAL(objectNameChanged(QString)),obj,SIGNAL(windowTitleChanged(QString)));
QObject::connect(obj,&QWidget::windowTitleChanged,[](QString str) {qDebug() << str;});
obj->setObjectName("ObjectName");
qDebug() << "But window title is"<< obj->windowTitle();
obj->show();
Output is:
"ObjectName"
But window title is "WindowTitle"
But there is no way to do something like:
connect(this,SIGNAL(someSignal()),this,SIGNAL(anotherSignal("with custom data")));
In this case, you need a separate slot.

Can anyone give me same someting to keep in mind while using signals and slots in Qt?

I am learning to program using Qt framework. When I writes some code have signals and slots involved, the events didn't seem to fire and the signals and slots didn't seem to work. It really me make me annoyed. Can you give me some cautions and warnnings about signals and slots in Qt?
slot declarations:
private slots:
void onFtpCmdFinish(int cmdId, bool error);
void onRealtimeFtpCmdsDone(bool error);
connection code:
ftpHandle = new QFtp( this );
connect(ftpHandle, SIGNAL(commandFinished(int, bool)), this, SLOT(onFtpCmdFinish(int, bool)));
connect(ftpHandle, SIGNAL(done(bool)), this, SLOT(onRealtimeFtpCmdsDone(bool)));
Thank you in advance!
In the future, if you ever happen to run into problems with your Qt signals and slots again, the contents of the following blog entry can turn out to be a real life-saver (or at least a very good starting point for your investigations):
http://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/
It meticulously lists 20 ways to debug/troubleshoot your signals and slots; follow this list and chances are high that you will eventually find out what's wrong.
I hope that helps.
You can only detect failed connect() at runtime.
A couple of tips:
defining QT-FATAL-WARNINGS=1 will cause Qt to assert and quit whenever it gets a connect that doesn't match.
Or wrapping each connect in:
bool ok = connect(……); QASSERT( ok);
Always check the return type, if its true then CONNECT successful else some thing wrong..
Don't forget about the fifth argument Qt::ConnectionType if you will write multithreaded applications

Resources