This is a quick one. While playing around with Server-Sent Events I've created this page to consume my Bohemian Rhapsody stream.
How it works
Before building this page I had created a stream that sends Queen's Bohemian Rhapsody lyrics as messages.
Those messages are sent obeying the time they would appear in the song. What this means is if you press play when the first verse is received you are able to listen to the song synced with the lyrics.
http://playground.thisisvini.com/bohemian-rhapsody-event-stream
Code
I intend to publish both server and client's source code as soon I have time for this.
The server was made using NodeJS (I need to improve it a little bit).
The client uses the native implementation of EventSource
to consume the stream. This is how it looks like:
const eventSource = new EventSource(STREAM_URL)
eventSource.onmessage = (message) => {
container.innerHTML = message.data
}
eventSource.onerror = (error) => {
container.innerHTML = 'Sorry! Something went wrong with the stream'
}
eventSource.addEventListener('started', (e) => {
status.innerHTML = 'Playing...'
})
eventSource.addEventListener('stopped', (e) => {
status.innerHTML = 'Stopped'
})
This is a minimum implementation for testing the stream.
- Lines 3-5 are a default handler. The one that is triggered by messages without
event
field defined. - Lines 7-9 "handle" errors.
- Lines 11-13 define a listener for events of type
started
. Every time astarted
is received the label in the bottom right corner of the page is changed to "Playing…". The same principle applies for the next listener.
This is how the raw stream looks like:
Limitations
To avoid complications I decided to set some limits to this stream:
- This stream only allows 100 concurrent clients
- A client is disconnected after 30 minutes
- When the song finishes all previous messages are deleted
I don't think usage will ever get close to those numbers.
Support
Server-Sent Events
is supported by most of the browsers.
In case you need support for other/older browsers you can use this polyfill.
If you want to dig a little bit more in Server-Sent Events
maybe this post could be of your interest.