简单的数据流服务端和客户端实现

网页客户端 :

<!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):

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  */
}

  

posted @ 2024-01-06 17:11  wsh3166Sir  阅读(6)  评论(0编辑  收藏  举报