亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

chatGPT前端流式輸出js實(shí)現(xiàn)三種方法—fetch、SSE、websocket

 更新時(shí)間:2024年07月27日 16:47:41   作者:又又愛拍照  
項(xiàng)目需要接入chatgpt提供的api,后端返回流式的字符,前端接收并實(shí)時(shí)顯示,在JavaScript中,使用Stream流通常指的是處理數(shù)據(jù)流的一種方式,它們?cè)试S數(shù)據(jù)被處理成塊,而不是一次性處理整個(gè)數(shù)據(jù)集,這對(duì)于處理大量數(shù)據(jù)或者來自網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)非常有用,

項(xiàng)目需要接入chatgpt提供的api,后端返回流式的字符,前端接收并實(shí)時(shí)顯示。在JavaScript中,使用Stream流通常指的是處理數(shù)據(jù)流的一種方式。Stream可以是可讀的、可寫的、或者既可讀又可寫的。它們?cè)试S數(shù)據(jù)被處理成塊,而不是一次性處理整個(gè)數(shù)據(jù)集,這對(duì)于處理大量數(shù)據(jù)或者來自網(wǎng)絡(luò)請(qǐng)求的數(shù)據(jù)非常有用。

一、fetch實(shí)現(xiàn)stream

fetch 本身不直接支持流式輸出,但你可以使用 ReadableStream 和 TextDecoder 等 Web Streams API 來實(shí)現(xiàn)類似的效果。

function streamOutput(msg) {
  // 發(fā)送 POST 請(qǐng)求
  fetch('url', {
    method:"POST",
    body:JSON.stringify({ "content": msg}),
    timeout: 0,
    dataType:"text/event-stream",
    headers:{
      "Content-Type":"application/json"
    },
  }).then(response => {
    // 檢查響應(yīng)是否成功
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // 返回一個(gè)可讀流
    return response.body;
  }).then(body => {
    disableLoading();
    const reader = body.getReader();
    // 讀取數(shù)據(jù)流
    function read() {
      return reader.read().then(({ done, value }) => {
        // 檢查是否讀取完畢
        if (done) {
          console.log('已傳輸完畢');
          return;
        }
        // 處理每個(gè)數(shù)據(jù)塊
        console.log('收到的數(shù)據(jù):', value);
        // 繼續(xù)讀取下一個(gè)數(shù)據(jù)塊
        read();
      });
    }
    // 開始讀取數(shù)據(jù)流
    read();
  }).catch(error => {console.error('Fetch error:', error);});
}

二、SSE實(shí)現(xiàn)(只支持GET請(qǐng)求)

在 SSE 中,瀏覽器通過發(fā)送 HTTP GET 請(qǐng)求到服務(wù)器上特定的 SSE 端點(diǎn)(endpoint),然后服務(wù)器通過該連接發(fā)送事件(event)和相關(guān)數(shù)據(jù)到客戶端,故SSE 主要使用 GET 請(qǐng)求。EventSource不支持發(fā)送請(qǐng)求頭,如果需要發(fā)送請(qǐng)求頭則要用EventSourcePolyfill。

在使用EventSourcePolyfill前需要引入 Server-Sent Events (SSE) 的 JavaScript 庫(kù)。

引入方式一:npm或yarn

npm install event-source-polyfill
yarn add event-source-polyfill

在js文件中引入

import EventSource from 'event-source-polyfill';

引入方式二:eventsource

下載倉(cāng)庫(kù):https://github.com/Yaffle/EventSource
注意:進(jìn)入src文件下載所需eventsource.js或eventsource.min.js文件,引入時(shí)注意路徑,如果是jsp文件用絕對(duì)路徑

<script type="text/javascript" src="/path/eventsource.js"></script>
function streamOutput() {
	  // 創(chuàng)建 EventSourcePolyfill連接,如果不需要發(fā)送請(qǐng)求頭可以使用EventSource即可
	const eventSource = new EventSourcePolyfill('url',{
		headers:{
      		"Content-Type":"application/json"
    	}
	});
	// 處理 SSE 消息
	eventSource.onmessage = function (event) {
	  console.log('接收SSE的消息:', event.data);
	  // 在這里處理接收到的流式數(shù)據(jù)
	};
	// 處理 SSE 連接打開事件
	eventSource.onopen = function (event) {
	  console.log('SSE連接完成:', event);
	};
	// 處理 SSE 連接關(guān)閉事件
	eventSource.onclose = function (event) {
	  console.log('SSE連接關(guān)閉:', event);
	};
	// 處理 SSE 錯(cuò)誤事件
	eventSource.onerror = function (error) {
	  console.error('SSE EventSource error:', error);
	};
}

三、websocket實(shí)現(xiàn)(url必須為ws或wss開頭的接口)

WebSocket 是一種全雙工通信協(xié)議,允許客戶端和服務(wù)器之間進(jìn)行實(shí)時(shí)的雙向通信,并且支持POST請(qǐng)求。但是值得注意的是WebSocket只支持ws或wss開頭的接口。WebSocket 握手時(shí)并沒有提供直接設(shè)置請(qǐng)求頭的標(biāo)準(zhǔn)方法,它的握手階段是由瀏覽器自動(dòng)處理的,因此你不能直接在創(chuàng)建 WebSocket 連接時(shí)設(shè)置請(qǐng)求頭,但可以通過通過 URL 參數(shù)傳遞的方式傳遞信息。

function streamOutput(msg) {
	 const socket = new WebSocket('url');
	// 連接打開時(shí)觸發(fā)
	socket.addEventListener('open', event => {
	  console.log('WebSocket連接完成:', event);
	  // 處理接收到的消息
	  socket.addEventListener('message', event => {
	    console.log('接收消息:', event.data);
	    // 在這里處理接收到的流式數(shù)據(jù)
	  });
	});
	// 連接關(guān)閉時(shí)觸發(fā)
	socket.addEventListener('close', event => {
	  console.log('WebSocket連接關(guān)閉:', event);
	});
	// 處理錯(cuò)誤時(shí)觸發(fā)
	socket.addEventListener('error', error => {
	  console.error('WebSocket error:', error);
	});
}

四、總結(jié)

相關(guān)文章

  • JS實(shí)現(xiàn)多重選項(xiàng)卡切換輪播圖

    JS實(shí)現(xiàn)多重選項(xiàng)卡切換輪播圖

    這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)多重選項(xiàng)卡切換輪播圖制作,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • canvas實(shí)現(xiàn)動(dòng)態(tài)小球重疊效果

    canvas實(shí)現(xiàn)動(dòng)態(tài)小球重疊效果

    在javascript運(yùn)動(dòng)系列中,詳細(xì)介紹了各種運(yùn)動(dòng),其中就包括碰壁運(yùn)動(dòng)。但是,如果用canvas去實(shí)現(xiàn),卻是另一種思路。本文將詳細(xì)介紹canvas動(dòng)態(tài)小球重疊效果。下面跟著小編一起來看下吧
    2017-02-02
  • 最新評(píng)論