Server Side Event – MDN example

One of the best ways to have server side communicate to the front end is the server side event, relatively to other options like a websocket, short/long polling. In this example provided on MDN (source code here), they have implemented a small backend by hosting a php application on a nginx server.

I have very limited experience with either technology but by following this great tutorial, I am able to get php working with a nginx server. After that, you drop both the backend (sse.php) and frontend (index.htmml) script to the same folder, you should be able to recreate the example as below.

Server Side

In the php code, it is surprising to me how easy it is to read through the code as the basic syntax is extremely similar to other programming languages. The echo ping statement will be executed every second and the echo data will be executed every counter time which is a random number between 1 and 10.

The only places to watch out is

header(“Content-Type: text/event-stream”)

php made it pretty clear that header must be set before any output is set. In the documentation of SSE

The server-side script that sends events needs to respond using the MIME type text/event-stream. Each notification is sent as a block of text terminated by a pair of newlines (“\n\n”). For details on the format of the event stream, see Event stream format.

ob_get_level()

Return the nesting level of output buffering which is 0 only when it is inactive.

ob_end_flush()

This function will send the topmost buffer content off and turn off the buffer. The flush command afterwards will flush the system output buffer.

Client Side

The code on the server side is even simpler. There are two functions that demonstrated the power of server side event. One is called onmessage and the other called addEventListener. The only difference is that the onmessage will be called literally every time there is a message from the server side and the addEventListener will only be called when there is a message with an event field.

The addEventListener makes it easier to build several different listeners based on different event types. Otherwise, we will need to use the onmessage method to write more logic inside to tell one event from the other which could add more overhead.

Long story short, the onmessage is a superset of the addEventListener.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s