Generally we use the most is the HTTP request, but the frequent request may be caused by the pressure of the service is very large, so today talk about WebSocket long connection, one sentence: simple
1. What is a long connection?
A: A request to connect, lifetime use, you can long-term to maintain the interaction of information, unless the service is hung
2, QT inside is how to use the WebSocket for long connection
① First add qt + = WebSockets to the Pro file
② #include <QWebSocket>
③ initialization
_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 "));
④ corresponding slot function
Disconnecting will trigger this slot function void mainwindow::ondisconnected () { _ptimer->start (); Ui->textedit->append ("WebSocket is Disconnected");} Successful connection will trigger this slot function void mainwindow::onconnected () { _ptimer->stop (); Ui->textedit->append ("Connect successful");} The message received from the service triggers this slot function void mainwindow::ontextreceived (QString msg) { ui->textedit->append (" Textreceivestring "+ msg);} Disconnecting will start the timer, triggering this slot function to reconnect void Mainwindow::reconnect () { ui->textedit->append ("WebSocket reconnected"); _pdatarecvws->abort (); _pdatarecvws->open (Qurl ("ws://localhost:8080"));}
QT uses WebSocket for long connections