QT uses WebSocket for long connections

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.