HTML5中使用EventSource實現服務器發送事件


在HTML5的服務器發送事件中,使用EventSource對象可以接收服務器發送事件的通知。

示例:

es.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
 7 <script src="https://cdn.bootcss.com/event-source-polyfill/0.0.9/eventsource.min.js"></script>
 8 </head>
 9 <body>
10 <ul id="list">
11 </ul>
12 <script>
13 var source = new EventSource("test1");
14 source.onmessage = function(event) {
15     var item = $("<li></li>").html(event.data);
16     $("#list").append(item);
17 }
18 </script>
19 </body>
20 </html>

 

服務端接收我用的是Spring MVC實現的:

Demo1Controller.java

 1 package com.test.controller;
 2 
 3 import java.util.Date;
 4 
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 @Controller
10 public class Demo1Controller {
11     
12     @ResponseBody
13     @RequestMapping(value="/test1",produces="text/event-stream;charset=UTF-8")
14     public String test6() {
15         return "retry:5000\ndata:" + new Date().toLocaleString() + "\n\n";
16     }
17 
18 }

 

頁面效果:

 

這個示例實現了每隔5秒鍾從服務器獲取當前服務器時間,並輸出到頁面上。

下面我解釋一下關鍵代碼:

es.html網頁第7行,是引入了eventsource.min.js腳本,加入這個腳本是為了讓IE8及以上版本的IE可以支持EventSource,EventSource在目前所有版本都不支持。在其他主流瀏覽器如谷歌,火狐等都是支持的

es.html網頁第13行,是創建EventSource對象,並建立和服務端請求test1的連接

es.html網頁第14行,是用來接收服務端發來的數據,並進行后續操作

java類第13行,需要在注解添加屬性produces="text/event-stream;charset=UTF-8",不然會報錯:EventSource's response has a charset ("iso-8859-1") that is not UTF-8. Aborting the connection.

java類第15行,是EventSource接收數據的固定格式:retry:${毫秒數}\ndata:${返回數據}\n\n,retry是指每隔多久請求一次服務器,data是指要接收的數據。注意這個retry參數不是必須的,如果不填寫,對應的瀏覽器會有一個默認間隔時間,谷歌默認是3000毫秒,也就是3秒鍾。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM