HTML5 SSEJason
Server-Sent Events
Automatically reconnects
Resumes reuses connections to the same URL
Avoids blocking other HTTP traffic
Browser Support
Server-Sent Events are supported in all major browsers. except Internet Explorer.
Concept
Server
EventSource
Client
2.Push data(text/stream)
1.定期重試 GET Request
3.資料送達時,觸發onmessage事件
DB
Receive Server-Sent Event Notifications
Client
var source = new EventSource("GetDateTime");
source.onmessage = function (e) {
$(".update-area").text(e.data);};
Server Push Data
Content-Type: text/event-stream
Text Encoding is UTF-8
Always start with “data:“
Each line should end in a single "\n" (except for the last, which should end with two).
Receive Server-Sent Event Notifications
Server :
public ActionResult GetDateTime(){
string notification = "data:message\n\n", return Content(notification, "text/event-stream");
}
Server Push Data
Example1
:這是註解行data: Event1 的資料
:這是註解行data: Event2 的資料data:是由兩行構成
Server Push Data Example1
StringBuilder notification = new StringBuilder();
notification.Append(": 這是註解行 \n");
notification.Append("data : Event1 的資料 \n\n");
notification.Append(": 這是註解行 \n");
notification.Append("data : Event2 的資料 \n");
notification.Append("data: 是由兩行構成 \n\n");
Question1
source.onmessage = function (e) {
var messageArray = TODO
$(".update-area").text(messageArray[0]);
};
Server Push Data Associating an ID with an event
Example2
id: evnet1
data: event1 資料
id: event2
data: event2 資料
The message event contains a e.lastEventId property.
Server Push Data Controlling the reonnection-timeout
Example3
retry: 10000
data: hello world
Server Push Data Spectifying an event name
Example4
event: userlogon
data: logon success
event: update
data: update success
Server Push Data
source.addEventListener('userlogon', function(e) {
console.log(e.data);
}, false);
source.addEventListener('update', function(e) {
console.log(e.data);
}, false);
Question2 How do you send Json data?
Server: data: TODO
Client:source.addEventListener('message', function(e){
var data = TODO
console.log(data.id, data.msg);
}, false);
Reference
http://www.w3schools.com/html/html5_serversentevents.asp w3schools
http://www.html5rocks.com/en/tutorials/eventsource/basics/ HTML5 ROCKS
Event
XXXX.Js
$("form").keydown(function(e){
if (window.event.KeyCode == 13) {
$("form").submit();
}
});