Adding metadata on connections

You can now attach metadata for each client that connects to a session. For example, you can add information about the connecting user. When a client connects to the session, all existing clients connected to the session can access the metadata for the new connection.

You add this metadata by passing it into the generate_token() method of the OpenTok server-side library. The metadata is then securely embedded in the token string. Here’s an example, using the OpenTok PHP library:

require_once ‘OpenTokSDK.php’;

$openTokSdk = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);
$sessionId = ‘your_session_ID’; // Replace with the correct session ID
$role = RoleConstants::PUBLISHER; // Set this to the correct role for the client.

$metadata = "userName=Bob,score=88"; // Replace this with the correct metadata.

$token = $openTokSdk->generate_token($sessionId, $role, $metadata);

When testing an app in the staging environment using a test token string (such as 'devtoken'), you can set the metadata when you call the Session.connect() method. Pass the metadata as the the connectionData property of the properties parameter of the method. However, when creating a user token (which is required in the production environment), you must attach the metadata when generating a token using the server-side library.

The format of the metadata string is up to you. It can be a JSON string, XML data, comma-delimited key-value pairs … whatever you’d like. There is a limit of 1000 characters.

When a client connects to a session, other clients can see the metadata for the connecting client. The Session object (in each client) dispatches a connectionCreated event, which has an array of Connection objects. The metadata string is the data property of the Connection object corresponding to the new client’s connection.

This is a great way to pass along information about the client that has joined the session. This information could include the user name or any other data that your application needs to share about individual clients.

For more information, see the OpenTok documentation (JavaScript developers and ActionScript developers).