利用qwebchannel实现Python和JS之间进行通信

要解决前后端交互问题,可以利用qwebchannel实现python和JS之间的通信
文章末尾附有简单的demo

1. 准备阶段

由于我的python使用的是Anaconda,内置了pyqt,因此直接引入即可。
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, pyqtSlot, QUrl
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView

在前端部分,引入qwebchannel.js(直接复制下面的代码自己新建一个文件即可)

"use strict";

var QWebChannelMessageTypes = {
   
    signal: 1,
    propertyUpdate: 2,
    init: 3,
    idle: 4,
    debug: 5,
    invokeMethod: 6,
    connectToSignal: 7,
    disconnectFromSignal: 8,
    setProperty: 9,
    response: 10,
};

var QWebChannel = function(transport, initCallback)
{
   
    if (typeof transport !== "object" || typeof transport.send !== "function") {
   
        console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
                      " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
        return;
    }

    var channel = this;
    this.transport = transport;

    this.send = function(data)
    {
   
        if (typeof(data) !== "string") {
   
            data = JSON.stringify(data);
        }
        channel.transport.send(data);
    }

    this.transport.onmessage = function(message)
    {
   
        var data = message.data;
        if (typeof data === "string") {
   
            data = JSON.parse(data);
        }
        switch (data.type) {
   
            case QWebChannelMessageTypes.signal:
                channel.handleSignal(data);
                break;
            case QWebChannelMessageTypes.response:
                channel.handleResponse(data);
                break;
            case QWebChannelMessageTypes.propertyUpdate:
                channel.handlePropertyUpdate(data);
                break;
            default:
                console.error("invalid message received:", message.data);
                break;
        }
    }

    this.execCallbacks = {
   };
    this.execId = 0;
    this.exec = function(data, callback)
    {
   
        if (!callback) {
   
            // if no callback is given, send directly
            channel.send(data);
            return;
        }
        if (channel.execId === Number.MAX_VALUE) {
   
            // wrap
            channel.execId = Number.MIN_VALUE;
        }
        if (data.hasOwnProperty("id")) {
   
            console.error("Cannot exec message with property id: " + JSON.stringify(data));
            return;
        }
        data.id = channel.execId++;
        channel.execCallbacks[data.id] = callback;
        channel.send(data);
    };

    this.objects = {
   };

    this.handleSignal = function(message)
    {
   
        var object = channel.objects[message.object];
        if (object) {
   
            object.signalEmitted(message.signal, message.args);
        } else {
   
            console.warn("Unhandled signal: " + message.object + "::" + message.signal);
        }
    }

    this.handleResponse = function(message)
    {
   
        if (!message.hasOwnProperty("id")) {
   
            console.error("Invalid response message received: ", 
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当使用UDP进行Python和C#之间通信时,你需要在两个应用程序中分别实现UDP的发送和接收功能。下面是一个简单的示例代码,演示了Python和C#之间通过UDP进行通信的过程。 Python端代码(发送端): ```python import socket def main(): target_ip = "192.168.1.100" # 目标IP地址 target_port = 1111 # 目标端口号 # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: message = input("请输入要发送的消息:") if message == "exit": break # 发送消息到目标IP和端口 sock.sendto(message.encode(), (target_ip, target_port)) sock.close() if __name__ == '__main__': main() ``` C#端代码(接收端): ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace udp_server { class Program { static int port = 1111; // 接收端口号 static void Main(string[] args) { Console.WriteLine("服务器启动....."); // 创建UDP套接字 UdpClient udpClient = new UdpClient(port); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, port); while (true) { // 接收消息 byte[] bytes = udpClient.Receive(ref remoteEP); string message = Encoding.UTF8.GetString(bytes); Console.WriteLine("接收到消息:" + message); } udpClient.Close(); } } } ``` 这个示例中,Python端通过创建UDP套接字,然后从用户输入读取消息,并将消息发送到指定的目标IP和端口。C#端通过创建UDP套接字,然后循环接收来自Python端发送的消息,并在控制台显示接收到的消息。 注意:在实际使用中,你需要根据具体的网络配置和需求进行适当的调整和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值