This tutorial describes how to use Pusher to expose a user's connection status. Optionally, it lets you or your users explicitly open and close the socket. With this functionality, you can tell your users whether the realtime features of your site are available or not.
Pusher has a rich JavaScript client that handles the nitty gritty of WebSocket connections. Today, we are releasing a new version. It emits events to expose the connection’s status. Optionally, it lets you or your users explicitly open and close the socket.
With this functionality, you can tell your users whether the realtime features of your site are available and, if they are not, if and when they might become available.
When the JavaScript client connects to Pusher, it emits the connected
event. Bind to this to let your users know that the lines of communication are now open.
1pusher.connection.bind('connected', function() { 2 alert("You don't need to shout.") 3});
If the client tries to connect and meets with failure, it issues a connecting_in
n seconds event, waits those n seconds and tries again. For each consecutive failure, the delay increases by two seconds, up to a maximum of ten seconds. In the interim, you can show the user a message telling them what is going on.
1pusher.connection.bind('connecting_in', function(delay) { 2 alert("Retrying in " + delay + " seconds.") 3});
If the user has just plugged in their internet connection, or come through a tunnel on a train, or emerged from a cave, they will know that their internet should now be working again. If you have exposed the new “connect now” functionality, they can use it to skip the connection attempt delay.
As well as the explicit connect command, there is a disconnect command. Expose this to let your users close the connection to Pusher. Upon closure, a closed
event is emitted that you can bind to and report what happened.
The failed
event indicates that the user has a browser that will not work with Pusher: Lynx, maybe, or Firefox without Flash. Bind to this event to tell the user that they are missing out on the realtime features of your site.
1pusher.connection.bind('failed', function() { 2 document.write("You're missing out on some cool stuff. Try a better browser.") 3});
The old state change events – pusher:connection_established
, pusher:connection_failed
and pusher:connection_disconnected
– are no longer available.
Also, if you need to access socket_id
, it is now available as pusher.connection.socket_id
.
This traffic light demonstrates the new features.
Read the documentation and link to the new pusher.js
version:
1<script src="http://js.pusherapp.com/1.9/pusher.js"></script>