参考网址?https://www.cnblogs.com/HTLucky/p/17326459.html
新建文件?httpsseClient.js
// 'use strict';
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { reactive } from "vue";
let eventSource = null;
const sseClientMsg = reactive({
? data: "",
});
const createSSClient = (callback = null) => {
? // createSSClientGet();
? createSSClientPost(callback);
};
const createSSClientGet = (callback = null) => {
? if (window.EventSource) {
? ? // 根据环境的不同,变更url
? ? const url = "http://139.155.59.51:48080";
? ? const curMessage = "";
? ? eventSource = new EventSource(`${url}/see_test`, { msg: curMessage });
? ? eventSource.onmessage = (e) => {
? ? ? const message = JSON.parse(e.data);
? ? ? //messages.push(message);
? ? ? console.log("已接受到消息:", e.data);
? ? };
? ? eventSource.onerror = (event) => {
? ? ? that.eventSource.close();
? ? };
? ? //处理服务器响应报文中的自定义事件
? ? eventSource.addEventListener("close", function (e) {
? ? ? that.eventSource.close();
? ? });
? } else {
? ? console.log("你的浏览器不支持SSE~");
? }
};
// await ?post方式
const createSSClientPost = (callback = null) => {
? fetchEventSource("http://139.155.59.51:48080/sse_test", {
? ? method: "POST",
? ? headers: {
? ? ? "Content-Type": "text/event-stream",
? ? },
? ? openWhenHidden: true,
? ? body: JSON.stringify({
? ? ? // 后端要的数据
? ? ? prompt: "",
? ? ? history: [],
? ? ? max_token: 2048,
? ? ? temperature: 0,
? ? ? top_p: 0.9,
? ? }),
? ? async onmessage(msg) {
? ? ? const { data } = msg;
? ? ? if (data && JSON.parse(data)) {
? ? ? ? if (callback) {
? ? ? ? ? callback(data);
? ? ? ? }
? ? ? }
? ? },
? ? onerror(err) {
? ? ? throw err;
? ? },
? });
};
export { createSSClient };
vue中调用方式
import { createSSClient } from "./js/httpsseClient.js";
const createSSClientOper = () => {
? sseClent.reciveData = "";
? createSSClient((msg) => {
? ? const result = JSON.parse(msg);
? ? const contentMsg = result.message; // 返回的数据赋值到页面
? ? sseClent.reciveData = `${sseClent.reciveData}<br/> ${contentMsg}`;
? ? const content = document.getElementById("content");
? ? // 页面被文字铺满后实现滚动效果
? ? content.scrollTop = content.scrollHeight;
? });
};