Real-time "Animation" Rendering on the Server Side


If we want to update a part of the data on the webpage in real time, what should we generally do? Obviously, it's server-side push, and the specific implementation technologies can be Websocket, Polling, SSE...

However, I once saw an article like this on HackerNews:

Stupid solutions: Live server push without JS

The author inserted an image on the webpage, which can display the current number of online users in real-time without refreshing the page. At first glance, it really feels quite magical!

This type of image is called MJPEG, which is essentially a JPEG animation in some sense. The browser itself also supports it. The principle is that in a single request, the server marks the Response Content-Type as multipart/X-Mixed-Replace and continuously sends a complete JPEG. Once the browser receives a new image, it refreshes the image, thus forming a video stream.

In this way, the principle is actually the same as the Server Side Event I shared before, except that SSE is constantly issuing text, while multipart/X-Mixed-Replace is issuing binary.

Following this idea, I implemented a server-side rendering service for Game of Life. No matter how many browser pages are launched, all pages will always see the same frame of the image!