The server cannot initiate communication with the client unless it is requested. This makes it challenging to develop web applications that behave like traditional desktop clients. For example, developing a web application to monitor a real-time status is very challenging. HTML5 is designed with a component known as Server-Sent Events. HTML 5 defines an application programming interface (API) for opening an HTTP connection for receiving push notifications from the webserver. Using Server-Sent Events, a web page automatically gets updates from a server without the client having to request the information.

Browser Support

Server-Sent Events are supported by all major browsers, such as Firefox, Chrome, Safari and Opera. Server-Sent Events are not supported by Internet Explorer.

Client-side JavaScript API

Server-Sent Events are sent over the HTTP protocol. No special protocols or ports are required to get this working. However, we do need the help of client-side and server-side scripting so that the client browser can interact with the web server. To subscribe to an event stream, create an EventSource object and pass it the URL of your stream. You also should consider checking to make sure the browser can support Server-Sent Events. The script first checks whether the browser supports Server-Sent events. If it does not, feedback is provided back to the user instead. If the browser does support the function, the Server-Sent Events will begin. The script creates an object of the EventSource class, passing it the URL of the server-side script that will be providing the streamed data updates. Then the script sets up an event listener function to execute when the EventSource object receives an update from the server. When this happens, the script simply gets a reference to the update page element and writes the new data to it. In this example, we only used the onmessage event. However, there are other events that you can use.

Server-side Scripts

On the server-side, you will need to have the web server capable of sending data updates. This is not possible with HTML code alone. You will need to incorporate a server-side scripting language such as ASP.NET, Classic ASP, or PHP. The syntax for the event stream coming from the web server is fairly simple. You should note that you will need to set the Content-Type header to text/event-stream. In the following PHP example, stream back to the web client, the time configured on the server.

Conclusion

In this tutorial, we have covered the basics of using Server-Sent events with HTML5, JavaScript, and PHP. In our example, we used our server-side script to generate the time on the web server. Of course, while not very useful, it does provide you with a starting point that you can incorporate into your own projects.

HTML5 Server Sent Events - 87