美文网首页
web客户端对接sse服务,实现打字效果

web客户端对接sse服务,实现打字效果

作者: 彩云飘过 | 来源:发表于2024-02-01 16:05 被阅读0次

    参考网址 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;

      });

    };

    相关文章

      网友评论

          本文标题:web客户端对接sse服务,实现打字效果

          本文链接:https://www.haomeiwen.com/subject/pxrzodtx.html