Sse

17
HTML5 SSE Jason

description

 

Transcript of Sse

Page 1: Sse

HTML5 SSEJason

Page 2: Sse

Server-Sent Events

Automatically reconnects

Resumes reuses connections to the same URL

Avoids blocking other HTTP traffic

Page 3: Sse

Browser Support

Server-Sent Events are supported in all major browsers. except Internet Explorer.

Page 4: Sse

Concept

Server

EventSource

Client

2.Push data(text/stream)

1.定期重試 GET Request

3.資料送達時,觸發onmessage事件

DB

Page 5: Sse

Receive Server-Sent Event Notifications

Client

var source = new EventSource("GetDateTime");

source.onmessage = function (e) {

$(".update-area").text(e.data);};

Page 6: Sse

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).

Page 7: Sse

Receive Server-Sent Event Notifications

Server :

public ActionResult GetDateTime(){

string notification = "data:message\n\n", return Content(notification, "text/event-stream");

}

Page 8: Sse

Server Push Data

Example1

:這是註解行data: Event1 的資料

:這是註解行data: Event2 的資料data:是由兩行構成

Page 9: Sse

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");

Page 10: Sse

Question1

source.onmessage = function (e) {

var messageArray = TODO

$(".update-area").text(messageArray[0]);

};

Page 11: Sse

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.

Page 12: Sse

Server Push Data Controlling the reonnection-timeout

Example3

retry: 10000

data: hello world

Page 13: Sse

Server Push Data Spectifying an event name

Example4

event: userlogon

data: logon success

event: update

data: update success

Page 14: Sse

Server Push Data

source.addEventListener('userlogon', function(e) {

console.log(e.data);

}, false);

source.addEventListener('update', function(e) {

console.log(e.data);

}, false);

Page 15: Sse

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);

Page 17: Sse

Event

XXXX.Js

$("form").keydown(function(e){

if (window.event.KeyCode == 13) {

$("form").submit();

}

});