首页 > 编程语言 >python+eel+ws实现消息推送

python+eel+ws实现消息推送

时间:2024-10-16 11:48:27浏览次数:1  
标签:function WebSocket python eel ws websocket message

ws服务器是单独的,专门用来推送消息。js用来连接ws,发消息。eel程序用户处理消息

ws服务器

import websockets
import asyncio

# 存储所有WebSocket连接的集合
connected_clients = set()

async def websocket_handler(websocket, path):
    # 将新的连接添加到集合中
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            print("收到消息,开始推送-》:", message)
            # 将收到的消息推送给所有连接的客户端
            await broadcast(message)
    finally:
        # 移除断开的连接
        connected_clients.remove(websocket)

async def broadcast(message):
    # 遍历所有连接的客户端,并将消息发送给每个客户端
    for client in connected_clients:
        if client.open:
            await client.send(message)

async def main():
    # 开启WebSocket服务器,并设置WebSocket处理器
    async with websockets.serve(websocket_handler, "localhost", 8000):
        await asyncio.Future()  # Run forever

if __name__ == '__main__':
    asyncio.run(main())

eel

import eel

@eel.expose
def handleMessage(message):
    #TODO 客户端处理消息
    print("收到服务器消息:", message)

eel.init('.')
eel.start('index.html', size=(600, 400),port=8888)

html

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Client</title>
    <script type="text/javascript" src="eel.js"></script>
</head>
<body>
    <h1>WebSocket Client</h1>
    <input id="msg" type="text"> <br>
    <button id="send" onclick="send()">发送消息</button>
    <div id="messages"></div>

    <script type="text/javascript">
        let ws;
        window.onload = function () {
            connectWS()
        }
        function connectWS() {
            ws = new WebSocket("ws://127.0.0.1:8000");
            ws.onopen = function() {
                writeToScreen("连接到服务器");
            };
            ws.onmessage = function(event) {
                handleServerMessage(event.data);
            };
            ws.onclose = function() {
            };
            ws.onerror = function(error) {
                writeToScreen("error: " + error);
            };
        }

        function handleServerMessage(message) {
            //展示在页面
            writeToScreen(message)
            //服务器处理消息,或者服务器处理完消息,再展示在页面,这里只是回显
            eel.handleMessage(message);
        }

        function writeToScreen(message) {
            const messagesDiv = document.getElementById("messages");
            const messageElement = document.createElement("div");
            messageElement.textContent = message;
            messagesDiv.appendChild(messageElement);
        }
        function send(){
            const messages = document.getElementById("msg").value;
            ws.send(messages)
            document.getElementById('msg').value = '';
        }

    </script>
</body>
</html>

标签:function,WebSocket,python,eel,ws,websocket,message
From: https://www.cnblogs.com/qcy-blog/p/18469587

相关文章

  • 已实现,python解密QRC歌词,加密歌词,解密
    一、LRC歌词格式LRC格式是一种常见的歌词文件格式,通常用于音乐播放器同步显示歌曲的歌词。LRC文件与音频文件配合使用,能够根据时间戳实时显示歌词,给用户带来更好的听歌体验。LRC格式的特点:时间戳:LRC歌词的核心是每行歌词前面的时间戳。时间戳的格式通常为#说明[mm:ss......
  • Windows系统部署redis自启动服务
    文章目录引言Iredis以本地服务运行(Windowsservice)使用MSI安装包配置文件,配置端口和密码IIredis服务以终端命令启动缺点运行redis-server并指定端口和密码III知识扩展确认redis-server可用性InstallingtheService引言服务器是Windows系......
  • [Python手撕]二叉搜索树中的众数
    给你一个含重复值的二叉搜索树(BST)的根节点root,找出并返回BST中的所有众数(即,出现频率最高的元素)。如果树中有不止一个众数,可以按任意顺序返回。假定BST满足如下定义:结点左子树中所含节点的值小于等于当前节点的值结点右子树中所含节点的值大于等于当前节点的值左......
  • python+eel入门示例
    安装eelpipinstalleelpyimporteelimportrandom#笑话列表jokes=["为什么电脑经常生病?因为窗户(Windows)总是开着!","为什么数学书看起来总是很悲伤?因为它里面有太多的问题(problems)","为什么海洋里没有电脑?因为它们总是遇到短路(seals)","为什么冰......
  • [Python手撕]环形子数组的最大和
    给定一个长度为n的环形整数数组nums,返回nums的非空子数组的最大可能和。环形数组意味着数组的末端将会与开头相连呈环状。形式上,nums[i]的下一个元素是nums[(i+1)%n],nums[i]的前一个元素是nums[(i-1+n)%n]。子数组最多只能包含固定缓冲区nums中......
  • Python 数据库备份脚本
    importdatetimeimportosimportsubprocess#数据库备份目录BACKUP_DIR='/path/to/backup'#备份文件保留周期(天)RETENTION_PERIOD=7#备份数据库defbackup_database():current_time=datetime.datetime.now()backup_file=f"backup_{current_time.strf......
  • python从0快速上手(十一)高级特性1
    Python学习:高级特性1在Python的奇妙世界里,高级特性就像是那些隐藏在角落里的神秘力量,等待着勇敢的程序员去发掘。装饰器、生成器和迭代器,这些听起来就像是古老魔法书中的咒语,但它们其实是Python中强大的编程工具。让我们一起揭开这些高级特性的神秘面纱,看看它们如何让我们......
  • 【新人系列】Python 入门(二):Python IDE 介绍
    ✍个人博客:https://blog.csdn.net/Newin2020?type=blog......
  • python pandas写入excel
    #--coding:utf-8--importdatetimeimportpandasaspdfromcommon_toolimportget_ip_areafromdb.mysqlConnectionimportMyPymysqlPoolfromdb_configimportdata_report_dbsex_dict={"-1":"未知","0":"女&......
  • python 实现旋转图片算法
    旋转图片算法介绍旋转图片算法是图像处理中常用的一种技术,它可以将图像中的对象旋转到特定的角度。这种算法在图像处理、计算机视觉、人工智能等领域都有广泛的应用,例如自动驾驶、医学影像、安防监控等场景。以下是旋转图片算法的基本步骤:确定旋转中心点:旋转操作通常围绕......