I try to call slot of my class via newConnection()
signal of QTcpServer
class. connect()
function returns true
, but the slot weren't executed.
Here's what i made:
class server : QObject
{
Q_OBJECT
public:
server();
QTcpServer *srv;
void run();
public slots:
void handleClient();
}
Bind the slot:
void server::run()
{
srv = new QTcpServer();
bool status = connect(srv, SIGNAL(newConnection()), this, SLOT(handleClient()));
// status contains true now
srv->listen(QHostAddress::Any, port);
}
Slot's body:
void server::handleClient()
{
/* This code is not being executed */
qDebug() << "zxc";
QMessageBox msg;
msg.setText("zxc");
msg.exec();
}
Why doesn't it work?
I'm not quite sure what you're doing wrong try adding public
in the inheritance line (: public QObject
).
The following code works for me:
server.hpp
#ifndef _SERVER_HPP_
#define _SERVER_HPP_
#include <QtNetwork>
class Server : public QObject
{
Q_OBJECT
public:
Server();
private slots:
void handleClient();
private:
QTcpServer* mServer;
};
#endif
server.cpp
#include "server.hpp"
Server::Server() : mServer(new QTcpServer())
{
connect(mServer, SIGNAL(newConnection()), this, SLOT(handleClient()));
mServer->listen(QHostAddress::Any, 10000);
}
void Server::handleClient()
{
while (mServer->hasPendingConnections())
{
QTcpSocket* skt = mServer->nextPendingConnection();
skt->write("READY\n");
skt->waitForReadyRead(5000);
qDebug() << skt->readAll();
skt->write("OK\n");
skt->waitForBytesWritten();
skt->close();
skt->deleteLater();
}
}
main.cpp
#include "server.hpp"
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
Server srv;
return app.exec();
}