Server-Sent Events (SSE) allow a website to receive updates from a server.
Server-Sent Events (SSE) allow a website to receive updates from a server .
Server-Sent Events - One-way messaging
Server-Sent Events are when a website automatically receives updates from the server.
This could have happened before, but the website would have had to ask if there were any updates. With Server-Sent Events, updates arrive automatically.
For example, Facebook/Twitter updates, stock price updates, news feed, sports results, etc.
Browser support
The numbers in the table indicate the browser version that first fully supported Server-Sent Events.
| API SSE |
Google Chrome | MS Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| 6.0 | 79.0 | 6.0 | 5.0 | 11.5 |
Receive Server-Sent Event notifications
The object EventSourceused to receive event notifications sent by the server:
For example:
var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "
"; };
The example is explained as follows:
- Create a new object
EventSourceand specify the URL of the page that submits updates (in this example, " demo_sse.php "). - Every time an update is received, the onmessage event will occur.
- When the onmessage event occurs, place the received data into the element with the id="result"
Check Server-Sent Events support
In the example above, there are some additional lines of code to check browser support for Server-Sent Events:
if(typeof(EventSource) !== "undefined") { // Yes! Server-sent events support! // Some code. } else { // Sorry! No server-sent events support. }
Example of server-side code
For the above example to work, you need a server capable of sending data updates (such as PHP or ASP).
Server-side event stream syntax is very simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.
Code in PHP (demo_sse.php):
Code in ASP (VB) (demo_sse.asp):
<% Response.ContentType = "text/event-stream" Response.Expires = -1 Response.Write("data: The server time is: " & now()) Response.Flush() %>
The code is explained as follows:
- Set the "Content-Type" header to "text/event-stream".
- Specify that the page should not be cached.
- Export data for sending (Always start with "data:" )
- Return the output data to the website.
EventSource object
In the examples above, the author used the onmessage event to receive the message. But other events are also available:
| Sự kiện | Mô tả |
|---|---|
| onopen | Khi kết nối với máy chủ được mở |
| onmessage | Khi một tin nhắn được nhận |
| onerror | Khi xảy ra lỗi |