0

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() 等)。服务器能够向客户端发送消息。谢谢。

4

1 回答 1

2

为了使用类必须继承的信号和插槽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){

}

根据文档

连接const QObject *sender,const char *signal,const QObject *receiver,const char *method,Qt::ConnectionType类型)

连接const QObject *sender,const char *signal,const char *method,Qt::ConnectionType类型)

connect ( const QObject *sender, PointerToMemberFunction信号, const QObject *receiver, PointerToMemberFunction方法, Qt::ConnectionTyp e 类型)

connect ( const QObject *sender, PointerToMemberFunction信号, Functor函子)

connect ( const QObject *sender, PointerToMemberFunction信号, const QObject *context, Functor functor, Qt::ConnectionType类型)

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

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)));
于 2017-07-16T18:52:35.957 回答