How to Automatically Reconnect Viewers to Your Millicast Stream

Millicast
Millicast
Published in
2 min readMar 30, 2019

With many live streaming use cases, dropped connections are sometimes a common occurrence. This post provides you with an example of how to deal with this problem by automatically reconnecting your viewers to your Millicast streams.

The auto-reconnect function can be handled directly in the viewer client. Using the video element and the onplay event, start an interval to check the currentTime property for the element the stream is attached to. If the currentTime property does not change, you can automatically fire the logic used to replay the stream.

Here’s an example:

let previousTime;
video.onplay = () => {
let si = setInterval(() => {
if (video.currentTime === previousTime) {
clearInterval(si);
//call play logic
return
}
previousTime = video.currentTime;
}, 5000);
};

Alternatively, you can handle this via WebSockets. Here’s an example using the events sent via the WebSocket to check whether a stream is still playing:

ws.onmessage = (message)=> {
let event = message.type;
let data = message.data;
let name = message.name;
switch(event){
case 'event':
let layers = data['layers'] !== null ? data['layers'] : {};
if(name === 'layers' && Object.keys(layers).length <= 0){
//call play logic or being reconnect interval
}
break;
}
};

If a subscriber connects and a publisher is not broadcasting, the “Feed not found” error can be caught and play logic can be looped.

Another option would be to create a middleware layer (e.g. Nodejs, PHP, ASP.NET, etc.) that both publishers and subscribers connect to via a WebSocket. The WebSocket server can then manage proxying requests to the Millicast service, and dispatching events to connected websocket clients based on the inbound request (publish, view, close). For example, if a publisher connects, the stream details for the broadcast can be stored and dispatched to viewers connecting to the same live stream to provide a uniform viewing experience.

We hope you found this tutorial helpful. Please feel free to comment with any feedback or suggestions.

-Team Millicast

--

--

Millicast
Millicast

The Fastest Streaming on Earth. Realtime WebRTC CDN built for large-scale video broadcasting on any device with sub-500ms latency.