0
在服務器端事件中,eventsource通過HTTP連接連接到服務器,並按文本/事件流格式接收事件,而不按照MDN文檔關閉連接。服務器端事件連接問題
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
我有下面的代碼 -
/**
*
*/
(function(){
\t "use strict"
\t var init = function(){
\t \t if (window.EventSource) {
\t \t \t console.log("Event source available");
\t \t \t var source = new EventSource('/message');
\t \t \t source.addEventListener('message', function(e) {
\t \t \t var container = document.getElementById("container");
\t \t \t container.innerHTML += e.data;
\t \t \t });
\t \t \t source.addEventListener('open', function(e) {
\t \t \t console.log("Connection was opened.");
\t \t \t }, false);
\t \t \t source.addEventListener('error', function(e) {
\t \t \t if (e.readyState == EventSource.CLOSED) {
\t \t \t console.log("Connection was closed.");
\t \t \t } else {
\t \t \t console.log(e.readyState);
\t \t \t }
\t \t \t }, false);
\t \t \t } else {
\t \t \t console.log("No SSE available");
\t \t \t }
\t }
\t init();
\t
})();
<!DOCTYPE html>
<html>
<head>
<title>Index file</title>
<script type="text/javascript" src="js/ssescript.js"></script>
</head>
<body>
\t This is the index file.
\t <div id="container"></div>
</body>
</html>
,並在服務器端的瀏覽器打開一個我使用Spring MVC
package com.example.controller;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AppController {
@RequestMapping("/message")
public String getMessage(HttpServletResponse response){
response.setContentType("text/event-stream");
Random r = new Random();
return "data:Testing 1,2,3 "+r.nextInt()+"\n\n";
}
}
每次新連接並關閉它。我們能否只打開一次EventSource連接並繼續從服務器推送數據?
似乎需要從瀏覽器的支持;) – Blank
我與谷歌的Chrome 50.0.2661.102 –
試了一下有關添加''@ResponseBody什麼你的控制器方法? – Blank