Latest web development tutorials

HTML5 Server-Sent Events (Server-Sent Events)

HTML5 server send events (server-sent event) allows web pages to get updates from the server.

Server-Sent Events - way messaging

Server-Sent event is the website automatically obtain updates from the server.

Previously may also do so, provided that the page had to ask if an update is available. The server sends the event, the update will arrive automatically.

Examples: Facebook / Twitter updates, valuation updates, new blog, tournament results and so on.

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers are supported by the server sends the event, in addition to Internet Explorer.

Receiving Server-Sent Event Notification

EventSource object is used to receive event notifications sent by the server:


var source=new EventSource("demo_sse.php");
    document.getElementById("result") + "<br>";

try it"

Analysis examples:

  • EventSource create a new object, and then send the update regulations URL of the page (in this case, "demo_sse.php")
  • Each receives an update, onmessage event occurs
  • When onmessage event occurs, the received data is pushed into the id "result" element in

Detection Server-Sent Events Support

The following examples, we write some additional code to detect the browser to the server to send events supported by:

if (typeof (EventSource)! == "undefined")
// Browser supports Server-Sent
//Some code .....
// Browser does not support Server-Sent ..

Examples of server-side code

To make the example above, you can run, you also need to be able to send data to update the server (such as PHP and ASP).

Syntax server-side event stream is very simple. The "Content-Type" header is set to "text / event-stream". You can now start sending the event flow.


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

ASP code (VB) (demo_sse.asp):

Response.Write("data: " & now())

Code explanation:

  • The header "Content-Type" is set to "text / event-stream"
  • Provision does not cache pages
  • Output transmission date (always "data:" at the beginning)
  • Refresh the page to output data

EventSource objects

In the above example, we used to get the message onmessage event. However, you can also use other events:

事件 描述
onopen 当通往服务器的连接被打开
onmessage 当接收到消息
onerror 当发生错误