简单的数据流服务端和客户端实现
网页客户端 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < meta http-equiv="X-UA-Compatible" content="IE=edge"> < meta name="viewport" content="width=device-width, initial-scale=1.0"> < title >流式读取内容</ title > </ head > < body > < p id="content">接收数据流流==></ p > </ body > < script > async function getRes() { const res = await fetch(`http://127.0.0.1:8080/test_stream`,{ method: "get", }); const reader = res.body.getReader(); const decoder = new TextDecoder(); let content=document.getElementById('content'); while(1) { // 读取数据流的第一块数据,done表示数据流是否完成,value表示当前的数 const {done, value} = await reader.read(); if (done) { console.log(`done?===>`, done); break; } let text = decoder.decode(value); // 打印文本内容 console.log(text, done); content.innerHTML = content.innerHTML +text } } function loopf() { getRes(). catch((er)=>{ console.log('捕获错误:'+er); loopf(); }) } ; loopf(); </ script > </ html > |
服务端(GO):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package main import ( "fmt" "net/http" "time" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Match([]string{ "POST" , "GET" }, "/test_stream" , func (c *gin.Context) { w := c.Writer header := w.Header() header.Set( "Content-Type" , "text/html" ) // header.Set("content-type", "text/json") header.Set( "charset" , "utf-8" ) header.Set( "Access-Control-Allow-Origin" , "*" ) //header.Set("Access-Control-Allow-Headers", "*") //header.Set("Access-Control-Allow-Methods", "*") w.WriteHeader(http.StatusOK) w.Write([]byte(` <html> <body> `)) w.(http.Flusher).Flush() // 这里对每次循环输出都进行Flush刷新输出 for i := 0; i < 20; i++ { w.Write([]byte(fmt.Sprintf(` <p>%d</p> `, i))) w.(http.Flusher).Flush() time.Sleep(1 * time.Second) } w.Write([]byte(` </body> </html> `)) w.(http.Flusher).Flush() }) r.Run( "127.0.0.1:8080" ) /*visit http://127.0.0.1:8080/test_stream */ } |
分类:
JavaScript
, GO
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话