HTML5
Server-Sent Events API
使用情境
即時股市
即時新聞
Server Client
http://xxx.csie.io
web
實作1
• Polling
簡單、快速
即時和負荷成正比
• Long-polling
負荷較低、較即時
server端較複雜
實作2
• Server-sent-event
與Long-polling相似
單向傳輸
• WebSocket
雙向傳輸
server 需支援協定
outline
• 簡介
• 如何使用 SSE
• DEMO
簡介
• 架構在http之上
• MIME type : text/event-stream
• 跨平台及瀏覽器 ( IE、edge 不支援 )
• 單向傳輸 ( Server => Client )
• 自動重新連線、自定義事件
傳送格式
• id:事件編號
• event:事件名稱
• data:傳送的資料
• retry:重新連線時間。
如:
echo "id: 100n";
echo "data: 'first event'nn";
echo "id:101n";
echo "retry: 10000n";
echo "data: 'second event'nn";
server 端 ( test.php )
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while(1)
{
$time = date('r');
echo "data: The server time is: {$time}nn";
flush();
sleep(3);
}
?>
Client端 ( index.html )
<script>
if (window.EventSource)
{
var source = new EventSource('test.php');
source.onmessage = function(event)
{
$("#result").innerHTML += event.data;
};
}
else
//瀏覽器不支援 SSE,使用傳統的 xhr polling
</script>
The server time is: Sun, 15 Nov 2015 12:31:10 +0000
The server time is: Sun, 15 Nov 2015 12:31:13 +0000
The server time is: Sun, 15 Nov 2015 12:31:16 +0000
The server time is: Sun, 15 Nov 2015 12:31:19 +0000
The server time is: Sun, 15 Nov 2015 12:31:22 +0000
…………………..
DEMO
Reference
• http://blogger.gtwang.org/2014/04/stream-updates-with-server-sent-events.html (HTML5 SSE API)
• http://www.w3schools.com/html/html5_serversentevents.asp
( HTML5 SSE API , w3c school )
• http://www.waylau.com/web-real-time-push-technology/
( web 多種推播技術比較 )
Q&A
面試題 – 前端工程師
JavaScript
• closure 是什麼? 應用在哪?
• prototype 是什麼? 試寫函式 "123".lionic(2) => 123123
• ajax 是什麼? 優缺點? 如何解決缺點?
• 用 jquery 更改 element 的 class、css
• angular 的 service 與 factory的差別?
• function、variable的初始化
nodejs
• 該如何寫同步的程式碼?
shellscript
面試題 – 前端工程師
C語言
• stack、heap
• 試寫link list的結構
• 試寫quick sort
其他
• global、local variable
• get、post的差別,優缺點?
• overloading、overriding?
• process、thread的差別?
• call by reference、call by pointer、call by value
• semaphore、Mutex
• i++ = ++j =k++ 每次的值
• 用10行內的組語寫兩個數字比大小的函式

Sse api

Editor's Notes

  • #7 架構在http之上=>不用特別設通訊協定或在伺服器端裝任何軟體