Posts in current category
May 03, 2021 13:10 HTML5
Server-sent Events is a one-way communication of events and data sent to clients by a server based on the WebSocket protocol.
The HTML5 server send event allows the web page to get updates from the server.
The Server-Sent event refers to a Web page that automatically gets updates from the server.
This may have been done before, provided that the page has to ask if an update is available. Updates arrive automatically by sending events through the server.
Examples: Facebook/Twitter updates, valuation updates, new blog postes, event results, and more.
All major browsers support server sending events, except Internet Explorer.
The EventSource object is used to receive notifications of events sent by the server:
Create a new EventSource object and specify the URL of the page that sent the update (in this case, "demo_sse.php")
Every time an update is received, an onmessage event occurs
When the onmessage event occurs, the received data is pushed into an element with id as "result"
In the following example, we wrote an additional piece of code to detect browser support for server sending events:
For the above example to work, you also need servers (such as PHPs and ASPs) that can send data updates.
The syntax of the server-side event flow is very simple. S et the Content-Type header to text/event-stream. Now you can start sending event streams.
the lt;pPHP code (demo_sse.php):
ASP Code (VB) (demo_sse.asp):
Set the header "Content-Type" to "text/event-stream"
The rule is not to cache pages
Output send date (always starting with "data: " )
Refresh the output data to the Web page
In the example above, we use the onmessage event to get the message. However, there are other events that you can use:
As we described at the beginning of this section, Server-sent Events is based on the WebSocket protocol, we'll continue to introduce you to HTML WebSocket in the next section of this tutorial!