HTML and CSS Reference
In-Depth Information
4.1. Server-sent events (SSE)
Server-sent events (SSE) allow the web server to create an event in the browser. The event
can contain raw data or it can be a notification or a ping. The API for SSE in the browser
is the event listener in JavaScript, created using the same addEventListener() meth-
od you'd use for any other event listener. The only difference is that instead of adding a
listener to the document object or an element, you add it to an instance of the new We-
bSocket object. Why is this any better than requesting new data with AJAX? SSE offers
two main advantages:
• The server drives communication.
• There's less overhead of repeatedly creating a connection and adding headers.
In this section you'll learn how to use SSE as you build a simple chat application. As the
section winds down, you'll also learn when it's good to use SSE and when another tool
might be better.
4.1.1. A simple SSE chat application
Server-sent events are delivered to the browser in the form of a special file the browser re-
quests by creating an EventSource object. Instead of a regular HTML file or image, the
browser requests an event stream. Normally, the server attempts to deliver any file as fast
as possible, but with the event stream the file is purposely delivered slowly. The browser
stays connected to the server for as long as the file takes to be delivered, and the server can
add data to the file at any time. This approach is identical to that used by the forever frame
technique (defined in appendix D ) except that instead of developers having to decide for
themselves how to format the response, the format is laid down in the HTML5 standard.
In return for following SSE conventions, you use the familiar addEventListener()
approach you'd use for any other events.
Server-sent events 9
Search WWH ::

Custom Search