c++/qt通过QWebChannel与JS/html网页端交互通信

星空上的鲸 2024-07-17 10:33:01 阅读 96

1、需要从网上下载两个文件

<code>websocketclientwrapper.cpp 和 websocketclientwrapper.h

websockettransport.cpp 和 websockettransport.h

2、QWebChannel注册通信通信类对象名:“MyWebTransPort”,js调用这个名进行通信;

3、js发送数据至c++调用函数:void RecvTextFromJs(const QString &text);

c++发送数据至js调用函数:void SignalSendToJs(QString text);

4、js/html网页作为客户端,c++/qt启动本地服务器作为服务端进行通信;

5、QT += webchannel websockets

备注:二者通信是点与点之间进行的一种双向互相通信的一种方式,通过qt特有的信号与槽进行接口调用通信。

亲测可用,话不多说上源码:

**

亲,感觉不错的话点个赞哦*

video

一、c++/qt端:

1、MainWindow.cpp

<code>#include "MainWindow.h"

#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)

: QMainWindow(parent)

, ui(new Ui::MainWindow)

{

ui->setupUi(this);

initWebTransPort();

connect(ui->pushButton,&QPushButton::clicked,[=](){

static int i =0;

i++;

QString text = QString("send to js file %1 号").arg(QString::number(i));

emit m_web_transport->SignalSendToJs(text);

UpdateTextMessage(text);

qDebug()<<text;

});

connect(m_web_transport,&WebTransport::SignalSendToUI,[=](QString text){

UpdateTextMessage("get text from js: " + text);

});

}

MainWindow::~MainWindow()

{

if(m_websocketServer)

m_websocketServer->close();

delete ui;

}

void MainWindow::UpdateTextMessage(QString text)

{

ui->textEdit->append(text);

}

void MainWindow::initWebTransPort()

{

//通信核心代码

QString serverPort = "8003";

// 建立一个websocket服务器

if(m_websocketServer == NULL)

m_websocketServer = new QWebSocketServer(QStringLiteral("MyServer"),QWebSocketServer::NonSecureMode,this);

quint16 port = serverPort.toUInt();

if(!m_websocketServer->listen(QHostAddress("127.0.0.1"),port))

{

qDebug()<<"faild to open web socket server!!!";

}

UpdateTextMessage("open web socket server suceess");

// wrap WebSocket clients in QWebChannelAbstractTransport objects

if(m_clientWrapper == NULL)

m_clientWrapper = new WebSocketClientWrapper(m_websocketServer);

// setup the channel

if(m_webchannel == NULL)

{

m_webchannel = new QWebChannel();

QObject::connect(this->m_clientWrapper,&WebSocketClientWrapper::clientConnected,m_webchannel,&QWebChannel::connectTo);

}

// 将通信类注册到channel

if(m_web_transport == NULL)

{

m_web_transport = new WebTransport(this);

m_webchannel->registerObject("MyWebTransPort",m_web_transport); //网页上调佣MyWebTransPort,即可连接槽函数通信

qDebug()<<"register MyWebTransPort channel success!!!!";

UpdateTextMessage("register MyWebTransPort channel success!!!!");

}

}

2、MainWindow.h

#ifndef MAINWINDOW_H

#define MAINWINDOW_H

#include <QWidget>

#include <QObject>

#include <QMainWindow>

#include <QtWebSockets/QWebSocketServer>

#include "websockettransport.h"

#include "websocketclientwrapper.h"

#include <QtWebChannel/qwebchannel.h>

#include <QDesktopServices>

#include "WebTransport.h"

QT_BEGIN_NAMESPACE

namespace Ui { class MainWindow; }

QT_END_NAMESPACE

class MainWindow : public QMainWindow

{

Q_OBJECT

public:

MainWindow(QWidget *parent = nullptr);

~MainWindow();

void UpdateTextMessage(QString text);

private:

void initWebTransPort();

private:

Ui::MainWindow *ui;

QWebSocketServer* m_websocketServer{nullptr};

WebSocketClientWrapper* m_clientWrapper{nullptr};

QWebChannel* m_webchannel{nullptr};

WebTransport* m_web_transport{nullptr};

};

#endif // MAINWINDOW_H

3、通信类

3.1 WebTransport .h

#ifndef WEBTRANSPORT_H

#define WEBTRANSPORT_H

#include <QObject>

//通信类对象

class WebTransport : public QObject

{

Q_OBJECT

public:

WebTransport(QObject*parent);

~WebTransport();

signals:

//用于发送给js页面的数据

void SignalSendToJs(QString text);

void SignalSendToUI(QString text);

public slots:

// js调用此函数 由于是异步通信,js端使用promise方式调用

// 接收JS传递过来的字符串

void RecvTextFromJs(const QString &text);

};

#endif //

3.2 WebTransport.cpp

#include "WebTransport.h"

#include <QDebug>

#include <QMessageBox>

WebTransport::WebTransport(QObject*parent)

:QObject(parent)

{

}

WebTransport::~WebTransport()

{

}

void WebTransport::RecvTextFromJs(const QString &text)

{

qDebug()<<"********** get text from js: "<<text;

emit SignalSendToUI(text);

}

二、JS/HTML网页端

1、从qt安装目录获取qwebchannel.js并与index.html放在同级目录

index.html

<!DOCTYPE html>

<html lang="en">code>

<head>

<meta charset="UTF-8" />code>

<link rel="icon" href="/favicon.ico" />code>

<meta name="viewport" content="width=device-width, initial-scale=1.0" />code>

<title>Vite App</title>

</head>

<body>

<div id="app"></div>code>

<button id="sendBtn" onclick="senBtnClicked();">发送</button>code>

<script type="module" src="/src/main.js"></script>code>

<script type="text/javascript" src="./src/qwebchannel.js"></script>code>

<script type="text/javascript">code>

window.onload = function()

{

if (location.search != "")

var baseUrl = (/[?&]webChannelBaseUrl=([A-Za-z0-9\-:/\.]+)/.exec(location.search)[1]);

else

var baseUrl = "ws://127.0.0.1:8003";

console.log("Connecting to WebSocket server: " + baseUrl + ".");

var socket = new WebSocket(baseUrl);

socket.onclose = function()

{

console.error("qwebchannel closed");

};

socket.onerror = function(error)

{

console.error("qwebchannel error: " + error);

};

socket.onopen = function()

{

console.log("WebSocket connected, setting up QWebChannel");

new QWebChannel(socket, function(channel)

{

console.log("Connected to WebChannel, ready to send/receive messages!");

//获取c++端注册的QWebChannel对象"MyWebTransPort"

window.core = channel.objects.MyWebTransPort;

//调用qt信号-SignalSendToJs(QString arg) 获取c++端发送的数据

window.core.SignalSendToJs.connect(function(msg)

{

console.log("接收Qt信息:" + msg);

});

});

}

}

function senBtnClicked(){

//点击html网页端发送按钮,调用qt槽函数RecvTextFromJs(QString arg) 发送下面数据至c++

core.RecvTextFromJs("hello,I am js file!!!!");

}

</script>

</body>

</html>



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。