QTcpServer 应用程序中 Qt C++ 中的槽和信号

Slots and signals in Qt C++ in QTcpServer app

QTcpServer 应用程序中存在有关 Qt C++ 中的槽和信号的问题。我对插槽和信号方法不是很熟悉。所以......问题是服务器应用程序上的客户端套接字插槽根本没有被调用。我认为我使用了错误参数的连接函数。

class CMyClient {
public:
    CMyClient();
    QTcpSocket* m_pClientSocket;
    MainWindow* m_pWin;
public slots:
    void onSocketReadyRead();
    void onSocketConnected();
    void onSocketDisconnected();
    void onSocketDisplayError(QAbstractSocket::SocketError);

我在这里使用连接函数:

void MainWindow::onNewConnection()
{
    CMyClient* pClient = new CMyClient();

    // set properties
    pClient->m_pClientSocket = m_pServSocket->nextPendingConnection();
    pClient->m_pWin = this;

    // events from client side on server side
    connect(pClient->m_pClientSocket, SIGNAL(readyRead()), SLOT(onSocketReadyRead()));
    connect(pClient->m_pClientSocket, SIGNAL(connected()), SLOT(onSocketConnected()));
    connect(pClient->m_pClientSocket, SIGNAL(disconnected()), SLOT(onSocketDisconnected()));
    connect(pClient->m_pClientSocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketDisplayError(QAbstractSocket::SocketError)));

... 但是这些连接功能不能正常工作。客户端正在连接,调用 onNewConnection 但来自客户端套接字的事件(槽)不会出现(readyRead() 等)。服务器能够向客户端发送消息。谢谢

为了使用信号和插槽 class 必须继承自 QObject,在您的情况下 CMyClient 您必须将其更改为类似于:

.*h

class CMyClient: public QObject {
    Q_OBJECT
public:
    CMyClient(QObject *parent= 0);
    QTcpSocket* m_pClientSocket;
    MainWindow* m_pWin;
public slots:
    void onSocketReadyRead();
    void onSocketConnected();
    void onSocketDisconnected();
    void onSocketDisplayError(QAbstractSocket::SocketError);
};

.cpp

CMyClient::CMyClient(QObject *parent): QObject(parent){

}

根据 documentation:

connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)

connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type)

connect(const QObject *sender,PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)

connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)

connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)

因此在您的情况下,缺少放置接收器对象。

CMyClient* pClient = new CMyClient(this);

connect(pClient->m_pClientSocket, SIGNAL(readyRead()), pClient, SLOT(onSocketReadyRead()));
connect(pClient->m_pClientSocket, SIGNAL(connected()), pClient, SLOT(onSocketConnected()));
connect(pClient->m_pClientSocket, SIGNAL(disconnected()), pClient, SLOT(onSocketDisconnected()));
connect(pClient->m_pClientSocket, SIGNAL(error(QAbstractSocket::SocketError)), pClient, SLOT(onSocketDisplayError(QAbstractSocket::SocketError)));