【发布时间】:2017-11-20 19:57:47
【问题描述】:
QAbstractSocketstateChanged()-Signal的正确使用/实现是什么?
main.cpp:
#include <QCoreApplication>
#include <sslserver.h>
#include <QLoggingCategory>
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
QLoggingCategory::setFilterRules("*.debug=true");
SslServer *myTestServer = new SslServer();
return a.exec();
}
SslServer.h:
#ifndef SSLSERVER_H
#define SSLSERVER_H
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
class SslServer : public QObject
{
Q_OBJECT
public:
explicit SslServer(QObject *parent = nullptr);
private slots:
void newTestConnection();
void sendTestdata();
void connectionWasClosed(QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState);
private:
QTcpServer *testServer;
QTcpSocket *testSocket;
QTimer *testTimer;
};
#endif // SSLSERVER_H
SslServer.cpp:
#include "sslserver.h"
#include <QDebug>
SslServer::SslServer(QObject *parent) : QObject(parent){
testServer = new QTcpServer(this);
testSocket = new QTcpSocket();
testTimer = new QTimer();
connect(testServer, SIGNAL(newConnection()), this, SLOT(newTestConnection())); //works
connect(testTimer, SIGNAL(timeout()), this, SLOT(sendTestdata())); //works
connect(testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(connectionWasClosed(QAbstractSocket::SocketState)));
//Qt5 Connection was also tested, without any change to old connection-typo
//connect(testSocket, &QAbstractSocket::stateChanged, this, &SslServer::verbindungWurdeBeendet);
testTimer->start(1000);
if(testServer->listen(QHostAddress::Any, 9999)){
qDebug() << "Server running on Port 9999";
}else{
qDebug() << "Error while building server";
}
}
void SslServer::newTestConnection(){
testSocket->close();
testSocket = testServer->nextPendingConnection();
testSocket->write("Welcome on: Testserver!");
testSocket->flush();
}
void SslServer::sendTestdata(){
if(testSocket->isOpen()){
qDebug() << testSocket->state();
qDebug() << "Sending testdata to client";
testSocket->write("testdata");
}
}
void SslServer::connectionWasClosed(QAbstractSocket::SocketState){
qDebug() << "!!! SocketState changed !!!";
}
我可以从 testSocket->state() 语句中看到状态正在从 Unconnected 变为 Connected 到 Unconnected ,但永远不会调用 SLOT-Function。我在这里错过了什么?
【问题讨论】:
-
尝试执行
qDebug() << (bool)connect(...)并查看该连接语句是否有效{true |错误的}。此外,也许您有多个套接字对象的实例。 -
您必须提供Minimal, Complete, and Verifiable example。您也可以通过 github、drive 或类似方式分享您的项目并发布链接。
-
上面分享的例子
-
@Papierschnellboot 查看我的回答:P
标签: c++ qt qt-signals qtcpsocket qt-slot