1 引入websocket

  1. QT += core gui websockets

2. 编写dialog.h头文件

  1. #ifndef DIALOG_H
  2. #define DIALOG_H
  3. #include <QDialog>
  4. #include <QWebSocket>
  5. QT_BEGIN_NAMESPACE
  6. namespace Ui { class Dialog; }
  7. QT_END_NAMESPACE
  8. class Dialog : public QDialog
  9. {
  10. Q_OBJECT
  11. public:
  12. Dialog(QWidget *parent = nullptr);
  13. ~Dialog();
  14. public slots:
  15. void createDataRecvWS(); /*-<创建websocket连接 */
  16. private:
  17. Ui::Dialog *ui;
  18. QWebSocket *dataRecvWS; /*-<websocket类 */
  19. private slots:
  20. void onConnected(); /*-<socket建立成功后,触发该函数 */
  21. void onTextReceived(QString msg); /*-<收到Sev端的数据时,触发该函数 */
  22. void onDisConnected(); /*-<socket连接断开后,触发该函数 */
  23. };
  24. #endif // DIALOG_H

3. 编写dialog.cpp源文件

  1. #include "dialog.h"
  2. #include "ui_dialog.h"
  3. #include <QDebug>
  4. Dialog::Dialog(QWidget *parent)
  5. : QDialog(parent)
  6. , ui(new Ui::Dialog)
  7. {
  8. ui->setupUi(this);
  9. dataRecvWS = Q_NULLPTR;
  10. }
  11. Dialog::~Dialog()
  12. {
  13. delete ui;
  14. }
  15. /**
  16. * @brief 创建websocket链接
  17. */
  18. void Dialog::createDataRecvWS() {
  19. if (dataRecvWS == Q_NULLPTR) {
  20. dataRecvWS = new QWebSocket();
  21. qDebug()<<"create websocket!";
  22. connect(dataRecvWS,&QWebSocket::disconnected,this,&Dialog::onDisConnected);
  23. connect(dataRecvWS,&QWebSocket::textMessageReceived,this,&Dialog::onTextReceived);
  24. connect(dataRecvWS,&QWebSocket::connected,this,&Dialog::onConnected);
  25. dataRecvWS->open(QUrl("ws://127.0.0.1:9000/ws"));
  26. }
  27. }
  28. /**
  29. * @breaf 判断连接状态
  30. * @note 当连接成功后,触发该函数
  31. */
  32. void Dialog::onConnected(){
  33. qDebug() << "DataReveive websocket is already connect!";
  34. qDebug() << "Address:" << dataRecvWS->peerAddress();
  35. dataRecvWS->sendTextMessage("Hello, server!!");
  36. }
  37. /**
  38. * @breaf 数据处理函数
  39. * @param msg, 数据信息
  40. * @note 当收到服务端发送的数据时,触发该函数
  41. */
  42. void Dialog::onTextReceived(QString msg){
  43. qDebug()<<"----------------data-----------------";
  44. qDebug()<<msg;
  45. }
  46. /**
  47. * @breaf 连接断开
  48. * @note 当连接断开时,触发该函数
  49. */
  50. void Dialog::onDisConnected(){
  51. qDebug()<<"Dialog websocket is disconnected!!!";
  52. }

QML中的websockets

  1. import QtQuick 2.0
  2. import Qt.WebSockets 1.0
  3. Text {
  4. width: 480
  5. height: 48
  6. horizontalAlignment: Text.AlignHCenter
  7. verticalAlignment: Text.AlignVCenter
  8. WebSocket {
  9. id: socket
  10. url: "ws://echo.websocket.org"
  11. active: true
  12. onTextMessageReceived: {
  13. text = message
  14. }
  15. onStatusChanged: {
  16. if (socket.status == WebSocket.Error) {
  17. console.log("Error: " + socket.errorString)
  18. } else if (socket.status == WebSocket.Open) {
  19. socket.sendTextMessage("ping")
  20. } else if (socket.status == WebSocket.Closed) {
  21. text += "\nSocket closed"
  22. }
  23. }
  24. }
  25. }