You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用WebSocket用JavaScript获取Python Socket服务的实时数据

实现方案:使用原生Server-Sent Events(SSE)

你可以使用浏览器原生支持的 Server-Sent Events (SSE) 实现需求,它是专为服务端单向推送数据设计的API,前后端都不需要引入任何第三方依赖,完全匹配你仅需服务端推送、客户端不需要发送数据的场景。

第一步:调整Python服务端

你原有的裸TCP Socket无法直接被浏览器JS访问,我们用Python标准库自带的http.server改造为符合SSE规范的服务,不需要安装额外第三方模块:

import time
import random
from http.server import BaseHTTPRequestHandler, HTTPServer

HOST = 'localhost'
PORT = 65432

class SSEHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # 设置SSE必需的响应头
        self.send_response(200)
        self.send_header('Content-Type', 'text/event-stream')
        self.send_header('Cache-Control', 'no-cache')
        self.send_header('Connection', 'keep-alive')
        # 允许跨域访问,本地调试用
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

        try:
            while True:
                timer = random.randint(1,3)
                value = random.randrange(999)
                time.sleep(timer)
                # SSE消息格式要求:以data:开头,两个换行结尾
                message = f'data: Slept {timer} seconds. Value: {value}\n\n'
                self.wfile.write(message.encode('utf-8'))
                self.wfile.flush() # 强制刷新缓冲区,立即发送数据
        except BrokenPipeError:
            # 客户端断开连接时退出
            pass

if __name__ == '__main__':
    server = HTTPServer((HOST, PORT), SSEHandler)
    print(f'SSE服务运行在 http://{HOST}:{PORT}')
    server.serve_forever()

第二步:前端原生JS实现接收展示

直接使用浏览器内置的EventSource对象接收推送数据,不需要引入任何第三方库:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>实时数据展示</title>
</head>
<body>
    <h3>服务端推送数据:</h3>
    <div id="dataContainer"></div>

    <script>
        const eventSource = new EventSource('http://localhost:65432');
        const container = document.getElementById('dataContainer');

        // 监听服务端推送的消息
        eventSource.onmessage = function(event) {
            const newItem = document.createElement('p');
            newItem.textContent = event.data;
            container.appendChild(newItem);
        };

        // 监听连接错误
        eventSource.onerror = function(error) {
            console.error('连接出错:', error);
            eventSource.close();
        };
    </script>
</body>
</html>

直接保存为HTML文件打开即可看到实时推送的效果。

补充说明:SSE默认会在连接断开后自动重连,如果你不需要这个特性,可以在错误回调里手动调用eventSource.close()关闭连接即可。

内容的提问来源于stack exchange,提问作者pptx704

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 09:15:04