EventSource
從服務端接受事件,下面是html代碼
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>comet</title> 5 </head> 6 <body> 7 <ul></ul> 8 <script> 9 var eventList=document.body; 10 var evtSource = new EventSource("sendMessage"); 11 //var evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } ); 12 /* evtSource.onmessage = function(e) { 13 var newElement = document.createElement("li"); 14 newElement.innerHTML = "message: " + e.data; 15 eventList.appendChild(newElement); 16 // alert( "message: " + e.data); 17 }*/ 18 19 evtSource.addEventListener("ping", function(e) { 20 var newElement = document.createElement("li"); 21 22 var obj = JSON.parse(e.data); 23 newElement.innerHTML = "ping at " + obj.time; 24 eventList.appendChild(newElement); 25 }, false); 26 27 evtSource.onerror = function(e) { 28 alert("EventSource failed."); 29 }; 30 31 </script> 32 </body> 33 </html> View Code注意eventSource對象的事件:
1.onopen:和服務器之間的鏈接打開時觸發
2.onmessage:當接收到信息時觸發
3.onerror:當發生錯誤時候觸發
下面是php代碼?
注意服務端代碼一定要設置Content-Type為text/event-stream類型。
默認的事件會一直執行,所以你要手動的關閉
evtSource.close();注意瀏覽器兼容性:
| EventSource support | 9 | 6.0?(6.0) | Not?supported | 11 | 5 |
當然,可以在代碼執行的時候判斷是否兼容
1 if(typeof(EventSource) !== "undefined") { 2 // Yes! Server-sent events support! 3 // Some code..... 4 } else { 5 // Sorry! No server-sent events support.. 6 }?
注意返回的數據的形式:
基本的形式如下:
data: My message\n\n多行數據的話每一行前面都要data:之后加上一個\n,最后一行是兩個\n。
data: first line\n data: second line\n\n上面返回的結果e.data是"first line\nsecond line"。接著e.data.split('\n').join('')?來去掉所有\n之后組成的新的string
//split(分割符)通過分割符將string變成數組
//jion將數組鏈接成string
發送json數據使用格式如下:
data: {\n data: "msg": "hello world",\n data: "id": 12345\n data: }\n\n在客戶端使用如下:
source.addEventListener('message', function(e) {var data = JSON.parse(e.data);console.log(data.id, data.msg); }, false);在發送的數據中添加id
可以為每次推送的信息中添加唯一的id(添加在信息開始處):
id: 12345\n data: GOOG\n data: 556\n\n設置id可以讓瀏覽器追蹤最后一次被觸發的事件,因為e.lastEventId?屬性存在。
控制重新鏈接的時間:瀏覽器會每3秒鐘進行一次重新連接
可以在data之前設置"retry:重新鏈接的毫秒數\n"來自定義重新連接的毫秒數.
下面設置重新鏈接的時間是10秒:
retry: 10000\n data: hello world\n\n指定事件名稱:
通過給事件名稱可以讓一個事件對象產生不同的時間類型。
"event:事件名"后面的data將和事件名相關聯。
例如下面的服務器輸出了三個事件類型,分別是:message,userlogon,update
data: {"msg": "First message"}\n\n event: userlogon\n data: {"username": "John123"}\n\n event: update\n data: {"username": "John123", "emotion": "happy"}\n\n客戶端的監聽是:
source.addEventListener('message', function(e) {var data = JSON.parse(e.data);console.log(data.msg); }, false);source.addEventListener('userlogon', function(e) {var data = JSON.parse(e.data);console.log('User login:' + data.username); }, false);source.addEventListener('update', function(e) {var data = JSON.parse(e.data);console.log(data.username + ' is now ' + data.emotion); }, false);?
轉載于:https://www.cnblogs.com/RachelChen/p/5431847.html
總結
以上是生活随笔為你收集整理的EventSource的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端入门面试题收集
- 下一篇: filter的原理(转)