概述Range 请求允许客户端只获取资源的部分字节范围,用于断点续传与媒体拖动。服务端需解析 `Range` 头并返回 `206 Partial Content` 与正确的 `Content-Range`。对不支持范围的资源返回 `200 OK` 或 `416 Range Not Satisfiable`。示例:客户端请求与服务端响应# 请求第 0–1023 字节 Range: bytes=0-1023 # 响应(部分内容) HTTP/1.1 206 Partial Content Content-Range: bytes 0-1023/123456 Accept-Ranges: bytes Content-Length: 1024 Node.js 示例(简化)import fs from 'node:fs' import http from 'node:http' http.createServer((req, res) => { const stat = fs.statSync('big.mp4') const range = req.headers['range'] res.setHeader('Accept-Ranges', 'bytes') if (!range) { res.writeHead(200, { 'Content-Length': stat.size, 'Content-Type': 'video/mp4' }) fs.createReadStream('big.mp4').pipe(res) return } const match = /bytes=(\d*)-(\d*)/.exec(range) let start = parseInt(match[1] || '0', 10) let end = parseInt(match[2] || (stat.size - 1) + '', 10) if (start > end || end >= stat.size) { res.writeHead(416, { 'Content-Range': `bytes */${stat.size}` }) return res.end() } res.writeHead(206, { 'Content-Range': `bytes ${start}-${end}/${stat.size}`, 'Content-Length': end - start + 1, 'Content-Type': 'video/mp4' }) fs.createReadStream('big.mp4', { start, end }).pipe(res) }).listen(8080) 工程建议验证与安全:校验范围合法性;对异常情况返回 `416` 与总长度;记录访问与速率限制。媒体协作:视频音频支持范围有助于进度跳转;与缓存/CDN 配合保持一致。可靠性:失败重试与并发分段下载需控制带宽与合并策略。参考与验证RFC 7233 Range Requests:https://www.rfc-editor.org/rfc/rfc7233MDN Range 请求文档:https://developer.mozilla.org/docs/Web/HTTP/Range_requests

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部