본문 바로가기

[R]HTML5 서버 전송 이벤트(HTML5 Server-Sent Events)

Server-Sent Events allow a web page to get updates from a server.

서버 보낸 이벤트 (Server-Sent Events)를 사용하면 웹 페이지가 서버에서 업데이트를 가져올 수 있습니다.




Server-Sent Events - One Way Messaging

서버 보낸 이벤트 - 편도 메시징


A server-sent event is when a web page automatically gets updates from a server.

서버 전송 이벤트는 웹 페이지가 자동으로 서버에서 업데이트를 가져 오는 경우입니다.

This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

이것은 이전에도 가능했지만 웹 페이지는 업데이트가 있는지 물어야했습니다. 서버 전송 이벤트를 사용하면 업데이트가 자동으로 실행됩니다.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

예 : Facebook / Twitter 업데이트, 주가 업데이트, 뉴스 피드, 스포츠 결과 등




Browser Support

브라우저 지원


The numbers in the table specify the first browser version that fully support server-sent events.

표의 숫자는 서버가 보낸 이벤트를 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.


API

SSE

6.0

Not supported

6.0

5.0

11.5




Receive Server-Sent Event Notifications

서버에서 보낸 이벤트 알림 수신


The EventSource object is used to receive server-sent event notifications:

EventSource 객체는 서버에서 보낸 이벤트 알림을 수신하는 데 사용됩니다.


Example

1
2
3
4
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
};
cs



Example explained:

예제 설명 :


Create a new EventSource object, and specify the URL of the page sending the updates (in this example "demo_sse.php")

새 EventSource 객체를 만들고 업데이트를 보내는 페이지의 URL을 지정하십시오 (이 예제에서는 "demo_sse.php").

Each time an update is received, the onmessage event occurs

업데이트가 수신 될 때마다 onmessage 이벤트가 발생합니다.

When an onmessage event occurs, put the received data into the element with id="result"

onmessage 이벤트가 발생하면 수신 된 데이터를 id = "result"




Check Server-Sent Events Support

서버 보낸 이벤트 지원 확인


In the tryit example above there were some extra lines of code to check browser support for server-sent events:

위의 tryit 예제에는 서버에서 보낸 이벤트에 대한 브라우저 지원을 확인하는 몇 가지 추가 코드 줄이 있습니다.


1
2
3
4
5
6
if(typeof(EventSource) !== "undefined") {
    // Yes! Server-sent events support!
    // Some code.....
} else {
    // Sorry! No server-sent events support..
}
cs




Server-Side Code Example

서버 측 코드 예제


For the example above to work, you need a server capable of sending data updates (like PHP or ASP).

위의 예제가 작동하려면 데이터 업데이트 (예 : PHP 또는 ASP)를 보낼 수있는 서버가 필요합니다.

The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.

서버 측 이벤트 스트림 구문은 간단합니다. "Content-Type"헤더를 "text / event-stream"으로 설정하십시오. 이제 이벤트 스트림을 보낼 수 있습니다.

Code in PHP (demo_sse.php):

PHP 코드 (demo_sse.php) :


1
2
3
4
5
6
7
8
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
 
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
cs


Code in ASP (VB) (demo_sse.asp):

ASP (VB) 코드 (demo_sse.asp) :


1
2
3
4
5
6
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
cs


Code explained:

설명 된 코드 :


Set the "Content-Type" header to "text/event-stream"

"Content-Type"헤더를 "text / event-stream"으로 설정하십시오.

Specify that the page should not cache

페이지가 캐시되지 않아야 함을 지정하십시오.

Output the data to send (Always start with "data: ")

전송할 데이터 출력 ( 항상 "data :"로 시작)

Flush the output data back to the web page

출력 데이터를 다시 웹 페이지로 플러시




The EventSource Object

EventSource 객체


In the examples above we used the onmessage event to get messages. But other events are also available:

위의 예제에서 onmessage 이벤트를 사용하여 메시지를 가져 왔습니다. 그러나 다른 이벤트도 사용할 수 있습니다.


Events Description
onopen When a connection to the server is opened
서버에 대한 연결이 열릴 때
onmessage When a message is received
메시지를 받으면
onerror When an error occurs
오류가 발생하면