HTML5 服务器发送事件(Server-Sent Events)

参考:HTML5 服务器发送事件(Server-Sent Events) | 菜鸟教程

一,sse介绍

Server-Sent 事件 - 单向消息传递

        Server-Sent 事件指的是网页自动获取来自服务器的更新。

以前也可能做到这一点,前提是网页不得不询问是否有可用的更新。通过服务器发送事件,更新能够自动到达。

例子:Facebook/Twitter 更新、股价更新、新的博文、赛事结果等。

项目目录:

二,服务端 main.py

        pip install flask

from flask import Flask, Response
import datetime
import time

app = Flask(__name__)

@app.route('/sse')
def send_server_time():
    def generate_server_time():
        while True:
            current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            yield f"data: The server time is: {current_time}\n\n"
            # 按需调整刷新频率,这里每秒发送一次
            sleep_duration = 3  # Use a different variable name to avoid conflict with the 'time' module
            time.sleep(sleep_duration)

'''配置响应内容类型、缓存控制及启动服务:
使用Response类包装生成器对象,指定mimetype为'text/event-stream',表示这是SSE响应。
添加响应头'Cache-Control': 'no-cache',防止浏览器缓存SSE消息。'''
    return Response(generate_server_time(), mimetype='text/event-stream',
                    headers={'Cache-Control': 'no-cache',
                             'Access-Control-Allow-Origin': '*',
                             'Access-Control-Allow-Headers': 'Content-Type,Authorization',
                             'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS'
                             })

if __name__ == '__main__':
    app.run(debug=False, port=5000)

三,web客户端 client.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
</head>

<body>
    <h1>获取服务端更新数据</h1>
    <div id="result"></div>

    <script>
        // 检测服务器发送事件的浏览器支持情况:
        if (typeof (EventSource) !== "undefined") {
            const eventSource = new EventSource('http://127.0.0.1:5000/sse');

            eventSource.onmessage = function (event) {
                const data = event.data;
                console.log('Received server time:', data);
                // 在此处更新DOM或执行其他操作以展示收到的时间信息
                document.getElementById("result").innerHTML += event.data + "<br>";
            };

            eventSource.onerror = function (error) {
                console.error('Error occurred with EventSource:', error);
            };
        }
        else {
            document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 server-sent 事件...";
        }
    </script>

</body>

</html>

四,测试

       启动服务端项目:python main.py 

       同时打开多个浏览器client.html

相关推荐

  1. HTML5 服务器发送事件Server-Sent Events)

    2024-04-26 09:40:03       38 阅读
  2. HTML 事件

    2024-04-26 09:40:03       7 阅读
  3. HTML:HTML事件汇总

    2024-04-26 09:40:03       16 阅读
  4. Qt event事件发送

    2024-04-26 09:40:03       33 阅读
  5. k8s发布nacos-server,nodeport配置注意事项

    2024-04-26 09:40:03       24 阅读
  6. HTML DOM 事件

    2024-04-26 09:40:03       7 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-26 09:40:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-26 09:40:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-26 09:40:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-26 09:40:03       18 阅读

热门阅读

  1. Elasticsearch索引别名:管理与优化数据访问

    2024-04-26 09:40:03       13 阅读
  2. log4j:WARN No appenders could be found for logger

    2024-04-26 09:40:03       11 阅读
  3. Ubuntu离线安装g++、locales

    2024-04-26 09:40:03       13 阅读
  4. Circuits--Sequential--Finite_2

    2024-04-26 09:40:03       12 阅读
  5. centos7 宝塔php7安装mongodb扩展

    2024-04-26 09:40:03       13 阅读
  6. 密码学系列0-总述

    2024-04-26 09:40:03       12 阅读
  7. mysql服务器无法启动问题处理

    2024-04-26 09:40:03       12 阅读
  8. 图神经网络 | Pytorch图神经网络ST-GNN

    2024-04-26 09:40:03       10 阅读
  9. Django项目之图书管理系统

    2024-04-26 09:40:03       8 阅读
  10. 中文语音识别实战(ASR)

    2024-04-26 09:40:03       11 阅读
  11. Spring

    Spring

    2024-04-26 09:40:03      9 阅读
  12. 【早晨读书会】深入理解rust并发编程

    2024-04-26 09:40:03       9 阅读
  13. FM33256

    2024-04-26 09:40:03       9 阅读