一般我们用的最多的就是http请求,但是频繁的请求可能对服务造成的压力很大,所以今天谈谈websocket长连接,一句话:简单
1、什么是长连接?
A:一次请求连接,终身使用,就可以长久的保持信息的交互,除非服务挂了
2、QT里面是如何使用websocket进行长连接的
①首先在pro文件里面添加QT += websockets
②#include <QWebSocket>
③初始化
_pdataRecvWS = new QWebSocket();
connect(_pdataRecvWS,SIGNAL(disconnected()),this,SLOT(onDisconnected()),Qt::AutoConnection);
connect(_pdataRecvWS,SIGNAL(textMessageReceived(QString)),this,SLOT(onTextReceived(QString)),Qt::AutoConnection);
connect(_pdataRecvWS,SIGNAL(connected()),this,SLOT(onConnected()),Qt::AutoConnection);
connect(_ptimer,SIGNAL(timeout()),this,SLOT(reconnect()),Qt::AutoConnection);
_pdataRecvWS->open(QUrl("ws://localhost:8080"));
④对应的槽函数
//断开连接会触发这个槽函数
void MainWindow::onDisconnected()
{
_ptimer->start(3000);
ui->textEdit->append("websocket is disconnected");
}
//连接成功会触发这个槽函数
void MainWindow::onConnected()
{
_ptimer->stop();
ui->textEdit->append("connect successful");
}
//收到服务发来的消息会触发这个槽函数
void MainWindow::onTextReceived(QString msg)
{
ui->textEdit->append("textReceiveString" + msg);
}
//断开连接会启动定时器,触发这个槽函数重新连接
void MainWindow::reconnect()
{
ui->textEdit->append("websocket reconnected");
_pdataRecvWS->abort();
_pdataRecvWS->open(QUrl("ws://localhost:8080"));
}