Connection
The Channels connection is the fundamental means of communication with the service. It is a bi-directional connection and is able to receive messages as well as emit messages from the server.
- JavaScript
- iOS
- Laravel Echo
When you create a new Pusher
object you are automatically connected to Channels.
1
var pusher = new Pusher('APP_KEY', options);
applicationKey
(String) - The application key is a string which is globally unique to your application. It can be found in the API Access section of your application within the Channels user dashboard.options
(Object) [optional] - See Channelsoptions
parameter below.
The options
parameter on the Pusher
constructor is an optional parameter used to apply configuration on a newly created Pusher
instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{ cluster: 'APP_CLUSTER', forceTLS: true, auth: { params: { param1: 'value1', param2: 'value2' }, headers: { header1: 'value1', header2: 'value2' } } }
The options are:
It’s possible to define if the connection should be made over TLS. For more information see Encrypting connections
Endpoint on your server that will return the authentication signature needed for private and presence channels. Defaults to '/pusher/auth'
.
For more information see authenticating users.
subscription_error
event is triggered on the channel. For more information see handling authentication problems.Defines how the authentication endpoint, defined using authEndpoint
, will be called. There are two options available:
- ajax - The default option where an
XMLHttpRequest
object will be used to make a request. The parameters will be passed asPOST
parameters. - jsonp - The authentication endpoint will be called by a
<script>
tag being dynamically created pointing to the endpoint defined byauthEndpoint
. This can be used when the authentication endpoint is on a different domain to the web application. The endpoint will therefore be requested as aGET
and parameters passed in the query string.
For more information see the Channel authentication transport section of the authenticating users docs.
The auth option lets you send additional information with the authentication request. See authenticating users.
When creating a Pusher
instance the options
parameter can have an auth
property set as follows:
1 2 3 4 5 6 7
var pusher = new Pusher('app_key', { auth: { params: { CSRFToken: 'some_csrf_token' } } });
Additional parameters to be sent when the channel authentication endpoint is called. When using ajax authentication the parameters are passed as additional POST
parameters. When using jsonp authentication the parameters are passed as GET
parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).
Only applied when using ajax authentication
Provides the ability to pass additional HTTP Headers to the channel authentication endpoint when authenticating a channel. This can be useful with some web application frameworks that guard against CSRF (Cross-site request forgery).
1 2 3 4 5 6 7
var pusher = new Pusher('app_key', { auth: { headers: { 'X-CSRF-Token': 'some_csrf_token' } } });
The identifier of the cluster your application was created in. When not supplied, will connect to the mt1
(us-east-1
) cluster.
1 2
// will connect to the 'eu' cluster var pusher = new Pusher('app_key', { cluster: 'eu' });
This parameter is mandatory when the app is created in a any cluster except mt1
(us-east-1
). Read more about configuring clusters.
Disables stats collection, so that connection metrics are not submitted to Pusher's servers.
Specifies which transports should be used by Channels to establish a connection. Useful for applications running in controlled, well-behaving environments. Available transports: ws
, wss
, xhr_streaming
, xhr_polling
, sockjs
. Additional transports may be added in the future and without adding them to this list, they will be disabled.
Specifies which transports must not be used by Channels to establish a connection. Useful for applications running in controlled, well-behaving environments. Available transports: ws
, wss
, xhr_streaming
, xhr_polling
, sockjs
. Additional transports may be added in the future and without adding them to this list, they will be disabled.
These can be changed to point to alternative Channels URLs (used internally for our staging server).
Ignores null origin checks for HTTP fallbacks. Use with care, it should be disabled only if necessary (i.e. PhoneGap).
After this time (in milliseconds) without any messages received from the server, a ping message will be sent to check if the connection is still working. Default value is supplied by the server, low values will result in unnecessary traffic.
After sending a ping message to the server, the client waits pongTimeout
milliseconds for a response before assuming the connection is dead and closing it. Default value is supplied by the server.
A Channels client can be configured to only connect over TLS connections. An application that uses TLS should use this option to ensure connection traffic is encrypted. It is also possible to force connections to use TLS by enabling the Force TLS setting within an application's dashboard settings.
The option to force TLS is available on all plans.
- JavaScript
- iOS
1
var pusher = new Pusher('app_key', { forceTLS: true } );
- JavaScript
When connection limits are reached additional connections over the limit will be rejected. You can capture the rejection by binding to the error
event on the pusher.connection
object.
1 2 3 4 5 6
var pusher = new Pusher('app_key'); pusher.connection.bind( 'error', function( err ) { if( err.error.data.code === 4004 ) { log('>>> detected limit error'); } });
It is also possible to disconnect from Channels.
- JavaScript
- iOS
- Java
- Laravel Echo
1
pusher.disconnect();
When working with our Channels client library, you can monitor the state of the connection so that you can notify users about expected behaviour.
- JavaScript
- iOS
pusher:connection_established
and pusher:connection_failed
.There are multiple ways to use the connection state API:
- Bind to individual state change events
- Bind to all state change events
- Query the state directly
Additionally, the reconnect mechanism is now more transparent. This means that you can display messages that tell the user when the service might be connected.
You can access the current state as pusher.connection.state
and bind to a state change using pusher.connection.bind('connected', function() {...})
State | Note |
---|---|
initialized | Initial state. No event is emitted in this state.", |
connecting | All dependencies have been loaded and Channels is trying to connect. The connection will also enter this state when it is trying to reconnect after a connection failure.", |
connected | The connection to Channels is open and authenticated with your app.", |
unavailable | The connection is temporarily unavailable. In most cases this means that there is no internet connection. It could also mean that Channels is down, or some intermediary is blocking the connection. In this state, pusher-js will automatically retry the connection every 15 seconds. |
failed | Channels is not supported by the browser. This implies that WebSockets are not natively available and an HTTP-based transport could not be found.", |
disconnected | The Channels connection was previously connected and has now intentionally been closed." |
Given a supported browser and functioning internet connection, the following states are expected:
1
initialized -> connecting -> connected
Temporary failure of the Channels connection will cause
1
connected -> connecting -> connected
If an internet connection disappears
1
connected -> connecting -> unavailable (after ~ 30s)
When the internet connection becomes available again
1
unavailable -> connected
In the case that Channels is not supported:
1
initialized -> failed
Each Channels instance now has a connection
object which manages the current state of the Channels connection and allows binding to state changes:
1 2 3 4 5
var pusher = new Pusher('_APP_KEY'); pusher.connection.bind('connected', function() { $('div#status').text('Realtime is go!'); });
You can also bind to the error
event, which is emitted whenever a connection error occurs:
1 2 3 4
pusher.connection.bind('error', function(error) { console.error('connection error', error) $('div#status').text('Error!'); });
There's an extra state_change
utility event that fires for all state changes:
1 2 3 4
pusher.connection.bind('state_change', function(states) { // states = {previous: 'oldState', current: 'newState'} $('div#status').text("Channels current state is " + states.current); });
- JavaScript
1
var state = pusher.connection.state;