Connecting basics
To make a connection to Diffusion™ Cloud the client must specify the host name and port number of Diffusion Cloud, the transport to use to connect, and whether that connection is secure.
The Diffusion Cloud API is an asynchronous API. As such, the client APIs for all languages provide asynchronous connect methods.
A subset of the Diffusion Cloud 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 of your Diffusion Cloud service. You can find this on your Diffusion Cloud Dashboard. For more information, see Administering Diffusion Cloud from the Diffusion Cloud Dashboard.
- port
- The port on which Diffusion Cloud accepts connections from clients. For secure connections use port 443. For standard connections use port 80.
- 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 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:
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) { ... } );
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 .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://diffractingmightyCarter.us.diffusion.cloud:80.
Use this URL to open the connection to Diffusion Cloud:
[PTDiffusionSession openWithURL:[NSURL URLWithString:@"url"] completionHandler:^(PTDiffusionSession *session, NSError *error) { // Check error is `nil`, then use session as required. // Ensure to maintain a strong reference to the session beyond the lifetime // of this callback, for example by assigning it to an instance variable. }];
Session session = Diffusion.sessions().open("url");
var session = Diffusion.Sessions.Open( "url" );
SESSION_T *session = session_create(url, NULL, NULL, &session_listener, NULL, NULL);
Connecting with multiple transports
In JavaScript, you can specify a list of transports. The client uses these transports to provide a transport cascading capability.
diffusion.connect({ host : 'host_name', transports : ['transport','transport','transport'] }).then(function(session) { ... } );
final Session session = Diffusion .sessions() .serverHost("host_name") .serverPort(port) .transports(transport, transport, transport) .open();
- The client attempts to connect using the first transport listed.
- If the connection is unsuccessful, the client attempts to connect using the next transport listed.
- 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:
transports: ['WS', 'XHR', 'WS']
.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 Diffusion Cloud.
Asynchronous connections
All Diffusion Cloud APIs can connect asynchronously to Diffusion Cloud:
diffusion.connect({ host : 'host_name', port : 'port' }).then(function(session) { ... } );
// Excluding the port from the URL defaults to 80, or 443 for secure connections [PTDiffusionSession openWithURL:[NSURL URLWithString:@"url"] completionHandler:^(PTDiffusionSession * newSession, NSError * error) { // Check error is `nil`, then use session as required. // Ensure to maintain a strong reference to the session beyond the lifetime // of this callback, for example by assigning it to an instance variable. }];
// openAsync returns a CompletableFuture that completes with a Session when a response is received from the server Diffusion.sessions().openAsync("url").thenApply(session -> { ... });
// Define a callback that implements ISessionOpenCallback and pass this to the open method Diffusion.Sessions.Open("url", callback );
/* * 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 Diffusion Cloud:
Session session = Diffusion.sessions().open("url");
var session = Diffusion.Sessions.Open( "url" );
SESSION_T *session = session_create(url, NULL, NULL, &session_listener, NULL, NULL);
When connecting to Diffusion Cloud 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 Diffusion Cloud, you can listen for session events to be notified when the session state changes. For more information about session states, see Session state.
JavaScript
- disconnect: The session has lost connection to Diffusion Cloud.
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
Diffusion Cloud.
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, Diffusion Cloud, 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.
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
- 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.
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.
// 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()); } });
// 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() ); } );
// 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);
This page last modified: 2020/06/25