Qt--QWebSocket判断是否连接成功

使用QWebsocket去连接server,首先在构造函数中做槽连接

HMWebSocket::HMWebSocket(QObject *parent) : QObject(parent)
{
    connect(&socketClient,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(&socketClient,SIGNAL(disconnected()),this,SLOT(closed()));
    socketClient.ignoreSslErrors();
}

在做好连接后,调用open(),去连接server,

bool HMWebSocket::open(QString &ip,int port)
{
    QString path = QString("ws://%1:%2").arg(ip).arg(port);
    QUrl url = QUrl(path);
    socketClient.open(url);

    return true;
}

调用open后,并不意味着连接server成功,而且qt的socket类没有提供判断是否连接成功的is函数,但是,一旦client与server连接成功,就会触发connected信号,所以,一但on

Connected槽被执行,就意味着连接成功了。

void HMWebSocket::onConnected()
{
    connect(&socketClient,&QWebSocket::textMessageReceived,this,&HMWebSocket::onTextMessageReceived);
//    socketClient.sendTextMessage("Hello word!");
    qDebug() << "hello word!";
}

当打印出“hello word”时,意味着连接成功。

你可能感兴趣的:(Qt,C/C++)