Just a second...

Connecting basics

To make a connection to the Diffusion™ server the client must specify the host name and port number of the Diffusion server, the transport to use to connect, and whether that connection is secure.

The Diffusion API is an asynchronous API. As such, the client APIs for all languages provide asynchronous connect methods.

A subset of the Diffusion APIs also provide synchronous connect methods: the Android™, Java™, .NET, and C APIs. In the following sections, all examples for these APIs are synchronous for simplicity. For asynchronous examples for these APIs, see Asynchronous connections.

Connection parameters

host
The host name or IP address of the system on which the Diffusion server is located.
port
The port on which the Diffusion server accepts connections from clients using the Unified API. You can configure which ports to provide connectors for in the Connectors.xml configuration file. For more information, see Connectors.xml.
transport
The transport used to make the connection. For example, WebSocket (ws). The transports your client can use to make a connection depend on the client library capabilities. For more information, see Platform support for the Diffusion Unified API libraries.
secure
Whether the connection is made over Secure Sockets Layer (SSL).

Connecting

In JavaScript®, Android and Java, you can define each of these parameters individually:

JavaScript
diffusion.connect({
    host : 'host_name',
    port : 'port', // If not specified, port defaults to 80 for standard connections or 443 for secure connections
    transports : 'transport', // If not specified, transports defaults to 'WS' and the client uses a WebSocket connection
    secure : false  // If not specified, secure defaults to false
}).then(function(session) { ... } );
Java and Android
final Session session = Diffusion
        .sessions()
        .serverHost("host_name")
	    // If no port is specified, the port defaults to 80 for standard connections or 443 for secure connections
	    // There is no default port for DPT. If you use the DPT transport, you must also define a port.
        .serverPort(port)
        // If no transports are specified, the connection defaults to use the WebSocket transport
        .transports(transport)
		// If not specified, secure transport defaults to false
        .secureTransport(false) 
        .open();

In Apple®, Android, Java, .NET and C, composite the host, port, transport, and whether the connection is secure into a single URL-style string of the following form: transport[s]://host:port.

For example, ws://diffusion.example.com:8080.

Use this URL to open the connection to the Diffusion server:

Apple
    // Excluding the port from the URL defaults to 80, or 443 for secure connections
    [PTDiffusionSession openWithURL:[NSURL URLWithString:@"ws://push.example.com"]
                  completionHandler:^(PTDiffusionSession * newSession, NSError * error)
     {
         if (newSession) {
             NSLog(@"Session open.");
             self.session = newSession;
         } else {
             NSLog(@"Session Failed to open with error: %@", error);
         }
     }];
                    
Java and Android
Session session = Diffusion.sessions().open("url");
.NET
var session = Diffusion.Sessions.Open( "url" );
C
SESSION_T *session = NULL;
session = session_create(url, NULL, NULL, &session_listener, NULL, NULL);
session_start(session, &error);

Connecting with multiple transports

In JavaScript, you can specify a list of transports. The client uses these transports to provide a transport cascading capability.

JavaScript
diffusion.connect({
    host : 'host_name',
    transports : ['transport','transport','transport']
}).then(function(session) { ... } );
Java and Android
final Session session = Diffusion
        .sessions()
        .serverHost("host_name")
        .serverPort(port)
        .transports(transport, transport, transport)
        .open();
  1. The client attempts to connect using the first transport listed.
  2. If the connection is unsuccessful, the client attempts to connect using the next transport listed.
  3. This continues until the one of the following events happens:
    • The client makes a connection
    • The client has attempted to make a connection using every listed transport. If this happens, the connection fails.

You can use specify that a client attempt to connect with a transport more than once. This enables you to define retry behavior. For example:

JavaScript
transports: ['WS', 'XHR', 'WS']
Java and Android
.transports(WEBSOCKET, WEBSOCKET, WEBSOCKET)

Transport cascading is useful to specify in your clients as it enables them to connect from many different environments. Factors such as the firewall in use, your end-user's mobile provider, or your end-user's browser can affect which transports can successfully make a connection to the Diffusion server.

Asynchronous connections

All Diffusion APIs can connect asynchronously to the Diffusion server:

JavaScript
diffusion.connect({
    host : 'host_name',
    port : 'port'
}).then(function(session) { ... } );
Apple
    // Excluding the port from the URL defaults to 80, or 443 for secure connections
    [PTDiffusionSession openWithURL:[NSURL URLWithString:@"url"]
                  completionHandler:^(PTDiffusionSession * newSession, NSError * error)
     {
         if (newSession) {
             NSLog(@"Session open.");
             self.session = newSession;
         } else {
             NSLog(@"Session Failed to open with error: %@", error);
         }
     }];
Java and Android
// Define a callback that implements SessionFactory.OpenCallback and pass this to the open method 
Diffusion.sessions().open("url", callback);
.NET
// Define a callback that implements ISessionOpenCallback and pass this to the open method
Diffusion.Sessions.Open("url", callback );
C
    /*
     * Asynchronous connections have callbacks for notifying that
     * a connection has been made, or that an error occurred.
     */
     SESSION_CREATE_CALLBACK_T *callbacks = calloc(1, sizeof(SESSION_CREATE_CALLBACK_T));
     callbacks->on_connected = &on_connected;
     callbacks->on_error = &on_error;

     session_create_async(url, principal, credentials, &session_listener, reconnection_strategy, callbacks, &error);

Synchronous connections

The following APIs can connect synchronously to the Diffusion server:

Java and Android
Session session = Diffusion.sessions().open("url");
.NET
var session = Diffusion.Sessions.Open( "url" );
C
SESSION_T *session = NULL;
session = session_create(url, NULL, NULL, &session_listener, NULL, NULL);
session_start(session, &error);

When connecting to the Diffusion server using the Android API, prefer the asynchronous open() method with a callback. Using the synchronous open() method might open a connection on the same thread as the UI and cause a runtime exception. However, the synchronous open() method can be used in any thread that is not the UI thread.

Managing your session

When your client has opened a session with the Diffusion server, you can listen for session events to be notified when the session state changes. For more information about session states, see Session state.

JavaScript

In JavaScript, listen for the following events on the session:
  • disconnect: The session has lost connection to the Diffusion server.

    The session state changes from CONNECTED_ACTIVE to RECOVERING_RECONNECT. This event is only emitted if reconnect is enabled.

  • reconnect: The session has re-established connection to the Diffusion server.

    The session state changes from RECOVERING_RECONNECT to CONNECTED_ACTIVE.

  • close: The session has closed. The provided close reason indicates whether this was caused by the client, the Diffusion server, a failure to connect, or an error.

    The session state changes to one of CLOSED_FAILED, CLOSED_BY_SERVER, or CLOSED_BY_CLIENT.

  • error: A session error occurs.
JavaScript
session.on('disconnect', function() {
    console.log('Lost connection to the server.');
});
session.on('reconnect', function() {
    console.log('Reconnected to the session on the server.');
});
session.on('close', function() {
    console.log('Session is closed.');
});
session.on('error', function() {
    console.log('A session error occurred.');
});

Apple

In Apple, the following boolean properties are available on the states that are broadcast through the default notification center for the application process and posted on the main dispatch queue:
  • isConnected: If true, the state is equivalent to the CONNECTED_ACTIVE state.
  • isRecovering: If true, the state is equivalent to the RECOVERING_RECONNECT state.
  • isClosed: If true, the state is one of CLOSED_FAILED, CLOSED_BY_SERVER, or CLOSED_BY_CLIENT.

The broadcast includes both the old state and new state of the session. It also includes an error property that is nil unless the session closure was caused by a failure.

Apple
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserverForName:PTDiffusionSessionStateDidChangeNotification
                object:session
                 queue:nil
            usingBlock:^(NSNotification * note)
{
    PTDiffusionSessionStateChange * change = note.userInfo[PTDiffusionSessionStateChangeUserInfoKey];
    NSLog(@"Session state change: %@", change);
}];

Other SDKs

In Android, Java, .NET, and C listen for changes to the session state. The listener provides both the old state and new state of the session. The states provided are those listed in the session state diagram. For more information, see Session state.

Java and Android
// Add the listener to the session
session.addListener(new Listener() {
    @Override
    public void onSessionStateChanged(Session session, State oldState, State newState) {
 
        System.out.println("Session state changed from " + oldState.toString() + " to " + newState.toString());
        
    }
});
.NET
// Add the listener to the session factory you will use to create the session
var sessionFactory = Diffusion.Sessions.SessionStateChangedHandler( ( sender, args ) => {

    Console.WriteLine( "Session state changed from " + args.OldState.ToString() + " to " + args.NewState.ToString() );
    
} );
C
// Define a session listener     
static void
on_session_state_changed(SESSION_T *session,
        const SESSION_STATE_T old_state,
        const SESSION_STATE_T new_state)
{
        printf("Session state changed from %s (%d) to %s (%d)\n",
               session_state_as_string(old_state), old_state,
               session_state_as_string(new_state), new_state);
}

// ... 

    // Use the session listener when opening your session
    SESSION_LISTENER_T session_listener = { 0 };
            session_listener.on_state_changed = &on_session_state_changed;

    session_create_async(url, principal, credentials, &session_listener, &reconnection_strategy, callbacks, &error);