Skip to content

Instantly share code, notes, and snippets.

@v2e4lisp
Created July 8, 2014 07:23
Show Gist options
  • Save v2e4lisp/d153df40ab7d0326cbf4 to your computer and use it in GitHub Desktop.
Save v2e4lisp/d153df40ab7d0326cbf4 to your computer and use it in GitHub Desktop.

Server-send Events(SSE) MEMO

supported browser

Reading

Client API

initialize

var src = new EventSource("/path/to/source");

connection open/close callback

src.onopen = function () {}
src.onclose = function () {}

listen on some event sent by server

src.addEventListener("event_1", function (event) {
  // ...
  // event.id
  // event.data
})

listent on events whose type is no specified

src.onmessage = function (event) {
	// ...
}

Server API


Should set Content-Type

header("Content-Type: text/event-stream\n\n");

Request & Response

=> Request
GET /stream HTTP/1.1 1
Host: example.com
Accept: text/event-stream

<= Response
HTTP/1.1 200 OK 2
Connection: keep-alive
Content-Type: text/event-stream
Transfer-Encoding: chunked

retry: 15000 3

data: First message is a simple string. 4

data: {"message": "JSON payload"} 5

event: foo 6
data: Message of type "foo"

id: 42 7
event: bar
data: Multi-line message of
data: type "bar" and id "42"

id: 43 8
data: Last message, id "43"

dashing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment