EventSource提供了三个标准事件,同时默认支持断线重连
事件 | 描述 |
---|---|
onopen | 当成功与服务器建立连接时产生 |
onmessage | 当收到服务器发来的消息时发生 |
onerror | 当出现错误时发生 |
传输的数据有格式上的要求,必须为 [data:...\n...\n]或者是[retry:10\n]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>sse</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- java基础工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
package com.et.sse.controller;
import cn.hutool.core.util.IdUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Controller
@RequestMapping("/chat")
public class ChatController {
Map<String, String> msgMap = new ConcurrentHashMap<>();
/**
* send meaaage
* @param msg
* @return
*/
@ResponseBody
@PostMapping("/sendMsg")
public String sendMsg(String msg) {
String msgId = IdUtil.simpleUUID();
msgMap.put(msgId, msg);
return msgId;
}
/**
* conversation
* @param msgId mapper with sendmsg
* @return
*/
@GetMapping(value = "/conversation/{msgId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter conversation(@PathVariable("msgId") String msgId) {
SseEmitter emitter = new SseEmitter();
String msg = msgMap.remove(msgId);
//mock chatgpt response
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
ChatMessage chatMessage = new ChatMessage("test", new String(i+""));
emitter.send(chatMessage);
Thread.sleep(1000);
}
emitter.send(SseEmitter.event().name("stop").data(""));
emitter.complete(); // close connection
} catch (IOException | InterruptedException e) {
emitter.completeWithError(e); // error finish
}
}).start();
return emitter;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChatGpt test</title>
<link rel="stylesheet" href="lib/element-ui/index.css">
<style type="text/css">
body{
background-color:white;
}
#outputCard{
height: 300px;
overflow:auto;
}
#inputCard{
height: 100px;
overflow:auto;
}
#outputBody{
line-height:30px;
}
.cursor-img{
height:24px;
vertical-align: text-bottom;
}
</style>
<script src="lib/jquery/jquery-3.6.0.min.js"></script>
<script src="lib/vue/vue.min.js"></script>
<script src="lib/element-ui/index.js"></script>
</head>
<body>
<h1 align="center">ChatGpt Test</h1>
<div id="chatWindow">
<el-row id="outputArea">
<el-card id="inputCard">
<div id="inputTxt">
</div>
</el-card>
<el-card id="outputCard">
<div id="outputBody">
<span id="outputTxt"></span>
<img v-if="blink" class="cursor-img" src="img/cursor-text-blink.gif" v-show="cursorImgVisible">
<img v-if="!blink" class="cursor-img" src="img/cursor-text-black.png" v-show="cursorImgVisible">
</div>
</el-card>
</el-row>
<el-row id="inputArea">
<el-col :span="21">
<el-input id="sendTxt" v-model="input" placeholder="input content" @keyup.native="keyUp"></el-input>
</el-col>
<el-col :span="3">
<el-button id="sendBtn" type="primary" :disabled="sendBtnDisabled" @click="sendMsg">send</el-button>
</el-col>
</el-row>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: '#chatWindow',
data: {
input: '',
sendBtnDisabled: false,
cursorImgVisible: false,
blink: true
},
mounted: function(){
},
methods: {
keyUp: function(event){
if(event.keyCode==13){
this.sendMsg();
}
},
sendMsg: function(){
var that = this;
//init
$('#outputTxt').html('');
var sendTxt = $('#sendTxt').val();
$('#inputTxt').html(sendTxt);
$('#sendTxt').val('');
that.sendBtnDisabled = true;
that.cursorImgVisible = true;
//send request
$.ajax({
type: "post",
url:"/chat/sendMsg",
data:{
msg: sendTxt
},
contentType: 'application/x-www-form-urlencoded',
success:function(data){
var eventSource = new EventSource('/chat/conversation/'+data)
eventSource.addEventListener('open', function(e) {
console.log("EventSource连接成功");
});
var blinkTimeout = null;
eventSource.addEventListener("message", function(evt){
var data = evt.data;
var json = JSON.parse(data);
var content = json.content ? json.content : '';
content = content.replaceAll('\n','<br/>');
console.log(json)
var outputTxt = $('#outputTxt');
outputTxt.html(outputTxt.html()+content);
var outputCard = $('#outputCard');
var scrollHeight = outputCard[0].scrollHeight;
outputCard.scrollTop(scrollHeight);
//cusor blink
that.blink = false;
window.clearTimeout(blinkTimeout);
//200ms blink=true
blinkTimeout = window.setTimeout(function(){
that.blink = true;
}, 200)
});
eventSource.addEventListener('error', function (e) {
console.log("EventSource error");
if (e.target.readyState === EventSource.CLOSED) {
console.log('Disconnected');
} else if (e.target.readyState === EventSource.CONNECTING) {
console.log('Connecting...');
}
});
eventSource.addEventListener('stop', e => {
console.log('EventSource连接结束');
eventSource.close();
that.sendBtnDisabled = false;
that.cursorImgVisible = false;
}, false);
},
error: function(){
that.sendBtnDisabled = false;
that.cursorImgVisible = false;
}
});
}
}
})
</script>
</html>