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

NodeJS使用SSE流式传输实时更新PNG图片的问题排查

基于SSE实现实时更新图片的问题修复方案

你的代码存在几处关键问题,导致SSE无法正常推送图片更新,以下是具体修改方案:

服务器端(server.js)修改

  1. 修正响应头:SSE的Content-Type必须是text/event-stream,原代码写错成iimage/png;base64(还有拼写错误),这是核心问题
  2. 替换阻塞式轮询:原代码的while(true)+同步wait会卡死Node.js事件循环,必须用setInterval实现异步定时更新
  3. 遵循SSE消息格式:SSE要求消息以data: 开头,结尾用\n\n分隔,不能直接输出base64字符串
  4. 修复Buffer创建方式:Node.js新版本中new Buffer()已废弃,改用Buffer.from()
  5. 增加错误处理:读取文件时捕获异常,避免服务崩溃

修改后的server.js代码:

const express = require('express')
const fs = require('fs')

const app = express()
app.use(express.static('public'))

app.get('/countdown', function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Access-Control-Allow-Origin': '*' // 跨域场景需要,本地测试可保留
  })

  // 立即推送一次当前图片
  sendImage(res)

  // 每200ms推送一次(和原代码间隔一致,可根据需求调整)
  const interval = setInterval(() => {
    sendImage(res)
  }, 200)

  // 客户端断开连接时清理定时器
  req.on('close', () => {
    clearInterval(interval)
    res.end()
  })
})

function sendImage(res) {
  try {
    const bitmap = fs.readFileSync("./public/pics/out.png");
    const base64 = Buffer.from(bitmap).toString('base64');
    // 按照SSE格式发送数据
    res.write(`data: ${base64}\n\n`)
  } catch (err) {
    console.error('读取图片失败:', err)
    res.write(`data: error\n\n`)
  }
}

app.listen(3000, () => console.log('SSE app listening on port 3000!'))

客户端(index.html)修改

  1. 修正DOM元素获取:原代码用getElementsByClassName("img"),但img标签的属性是id="img",应该用getElementById("img")
  2. 正确使用SSE消息数据:赋值图片src时要用e.data(服务器推送的base64内容),不是变量本身
  3. 确保DOM加载完成:把脚本放在img元素之后,避免找不到元素
  4. 增加错误监听:处理SSE连接错误,方便排查问题

修改后的index.html代码:

<html>
<head>
</head>
<body>
  <img id="img" src="" alt="实时更新图片">
  <script>
    if (!!window.EventSource) {
      const source = new EventSource('/countdown')
      const imgElement = document.getElementById("img")

      source.addEventListener('message', function(e) {
        if (e.data !== 'error') {
          imgElement.src = "data:image/png;base64," + e.data
        }
      }, false)

      source.addEventListener('error', function(e) {
        console.error('SSE连接出错:', e)
        if (e.readyState === EventSource.CLOSED) {
          console.log('SSE连接已关闭')
        }
      }, false)
    } else {
      console.log("你的浏览器不支持SSE")
    }
  </script>
</body>
</html>

额外说明

  • 确保./public/pics/out.png路径正确,Python脚本确实在每秒更新这个文件
  • 如果Python脚本更新文件时存在写入不完整的情况,可以在服务器端增加文件读取的重试逻辑,或者让Python写入临时文件后再替换目标文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:05:27