SSE介绍及使用(Server-Send Events)

一 介绍

SSE类似于WebSocket,用于服务端主动向客户端发送消息,保持长连接。而传统的HTTP,是客户端向服务端发送消息后,服务端再响应数据给客户端,且每次都需要客户端发起请求。

服务器发送事件 (SSE) 是一种简单的技术,用于为特定的 Web 应用程序实现服务器到客户端的异步通信。

SSE与WebSocket联系

SSE 是一种在基于浏览器的 Web 应用程序中仅从服务器向客户端发送文本消息的技术。SSE基于 HTTP 协议中的持久连接, 具有由 W3C 标准化的网络协议和 EventSource 客户端接口,作为 HTML5 标准套件的一部分。

WebSocket 是一种在 Web 应用程序中实现同时、双向、实时通信的技术。WebSocket 基于 HTTP 以外的协议(TCP),因此可能需要额外设置网络基础设施(代理服务器、NAT、防火墙等)。户端通过Http协议请求,在握手阶段升级为WebSocket协议。

java语言使用SSE实现监听远程服务端数据

引入依赖

xml 复制代码
 <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp-sse</artifactId>
    <version>4.12.0</version>
 </dependency>
 <dependency>
   <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.3</version>
 </dependency>

代码:

java 复制代码
package com.ts.sse.demos.web;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;


import java.util.concurrent.TimeUnit;

/**
 * @Author:sgw
 * @Date:2024/3/19
 * @Description: SSE客户端接收消息
 */
public class MySseController {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(50, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.MINUTES)
                .build();

        EventSource.Factory factory = EventSources.createFactory(client);
        // 请求体
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("prompt","哈喽,你好");
//        map.put("history", Arrays.asList());
//        map.put("temperature",0.9);
//        map.put("top_p",0.7);
//        map.put("max_new_tokens",4096);
//        String json = JsonUtil.objectToString(map);
        //RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),"");

        // 请求对象
        Request request = new Request.Builder()
                .url("http://192.168.110.21:8080/v0/api/")
                .get()
                .build();

        // 自定义监听器
        EventSourceListener eventSourceListener = new EventSourceListener() {
            @Override
            public void onOpen(EventSource eventSource, Response response) {
                System.out.println("开启链接");
                super.onOpen(eventSource, response);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                System.out.println("接收到的远程服务端推送的数据" + data);
                //   接受消息 data
                super.onEvent(eventSource, id, type, data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
                System.out.println("关闭连接");
                super.onClosed(eventSource);
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                System.out.println("连接失败");

                super.onFailure(eventSource, t, response);
            }
        };

        // 创建事件
        EventSource eventSource = factory.newEventSource(request, eventSourceListener);
    }
}
相关推荐
廋到被风吹走3 小时前
【Spring】AOP深度解析:代理机制、拦截器链与事务失效全解
java·spring·缓存
没有天赋那就反复3 小时前
JAVA length
java·开发语言·算法
步步为营DotNet3 小时前
深度探索.NET 中ValueTask:优化异步性能的轻量级利器
java·spring·.net
栈与堆3 小时前
LeetCode-88-合并两个有序数组
java·开发语言·数据结构·python·算法·leetcode·rust
董世昌413 小时前
添加、删除、替换、插入元素的全方法指南
java·开发语言·前端
小当家.1054 小时前
JVM八股详解(上部):核心原理与内存管理
java·jvm·学习·面试
heartbeat..4 小时前
Spring 声明式事务:原理、使用及失效场景详解
java·spring·面试·事务
寻星探路4 小时前
【Python 全栈测开之路】Python 基础语法精讲(三):函数、容器类型与文件处理
java·开发语言·c++·人工智能·python·ai·c#
xiaolyuh1234 小时前
【XXL-JOB】执行器 Netty服务 & Tomcat 进程+资源共用详解
java·tomcat
jasnet_u4 小时前
SpringCloudAlibaba的web微服务快速搭建
java·springboot·springlcoud