HTML5 server sends events


Release date:2024-02-21 Update date:2024-02-23 Editor:admin View counts:44

Label:

HTML5 server sends events

The HTML5 server sends an event that allows a web page to get updates from the server.

Server-Sent event-one-way messaging

Server-Sent an event means that a web page automatically gets updates from the server.

It was possible to do this in the past, as long as the page had to ask if any updates were available. Updates can arrive automatically by sending events through the server.

Examples: Facebook/Twitter updates, stock price updates, new blog posts, race results, etc.

Browser support

Internet Explorer Firefox Opera Google Chrome Safari

All major browsers support sending events from the server, except for Internet Explorer.

Receive Server-Sent event notifications

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

Example

varsource=newEventSource("demo_sse.php");source.onmessage=function(event){document.getElementById("result").innerHTML+=event.data+"<br>";};

Instance resolution:

  • Create a new EventSource object, and then specify the URL of the page that sent the update (“demo_sse.php” in this case)

  • Every time an update is received, it occurs onmessage event

  • When onmessage the event occurs, push the received data into the element whose id is “result”

Detect Server-Sent event support

For the following example, we wrote an additional piece of code to detect browser support for events sent by the server:

if(typeof(EventSource)!=="undefined")
{
    // Browser supports Server Server
    // Some code.....
}
else
{
    // Browser does not support Server Server..
}

Server-side code example

In order for the above example to work, you also need servers (such as PHP and ASP) that can send data updates.

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

Example

<?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.ContentType="text/event-stream"
Response.Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>

Code interpretation:

  • Set the header “Content-Type” to “text/event-stream”

  • Stipulate that pages are not cached

  • Output date sent (always starts with “data:”)

  • Refresh output data to a web page

EventSource object

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

Event

Description

Onopen

When the connection to the server is opened

Onmessage

When a message is received

Onerror

When something goes wrong

Powered by TorCMS (https://github.com/bukun/TorCMS).