Quickstart

Updated

Rapidly develop your first Signaling app.

Use Signaling SDK to add low-latency, high-concurrency signaling and synchronization capabilities to your app.

Signaling also helps you enhance the user experience in Video Calling, Voice Calling, Interactive Live Streaming, and Broadcast Streaming applications.

This page shows you how to use the Signaling SDK to rapidly build a simple application that sends and receives messages. It shows you how to integrate the Signaling SDK in your project and implement pub/sub messaging through Message channels. To get started with stream channels, follow this guide to create a basic Signaling app and then refer to the Stream channels guide.

Understand the tech

To use Signaling features in your game, you initialize a Signaling client instance and add event listeners. To connect to Signaling, you login using an authentication token. To send a message to a message channel, you publish the message. Signaling creates a channel when a user subscribes to it. To receive messages other users publish to a channel, your game listens for events.

To create a pub/sub session for Signaling, implement the following steps in your game:

Prerequisites

To implement the code presented on this page you need to have:

  • An Agora account and project.

  • Enabled Signaling in Agora Console

  • Unity Hub

  • Unity Editor 2018.4.0 or higher

  • Operating System and compiler requirements:

    Development PlatformOperating system versionCompiler version
    AndroidAndroid 4.1 or aboveAndroid Studio 3.0 or above
    iOSiOS 11.0 or aboveXcode 9.0 or above
    macOSmacOS 10.10 or aboveXcode 9.0 or above
    WindowsWindows 7 or aboveMicrosoft Visual Studio 2017 or above
  • Ensure that a firewall is not blocking your network communication.

Signaling 2.x is an enhanced version compared to 1.x with a wide range of new features. It follows a new pricing structure. See Pricing for details.

Project setup

Create a project

  1. In Unity Hub, select Projects, then click New Project.

  2. In All templates, select 3D. Set the Project name and Location, then click Create Project.

  3. In Projects, double-click the project you created. Your project opens in Unity.

Integrate the SDK

  1. Download the latest version of the Agora Signaling SDK, and unzip the contents to a local folder.

  2. In Unity, click Assets > Import Package > Custom Package.

  3. Navigate to the Signaling SDK package and click Open.

  4. In Import Unity Package, click Import.

Create a user interface

To create a simple UI for verifying the basic features of Signaling, add the following elements to your interface:

SampleScene

- Main Camera
- Canvas
 - Image            // Window background
 - Txt1             // Text label, text content is Send string message to message channel
 - InputField1      // Message input box
 - Btn1             // Send message
 - Txt2             // Text label, text content is Send binary message to stream channel
 - Btn2             // Create Stream Channel
 - Btn3             // Join Stream Channel
 - Btn4             // Join Topic
 - Btn5             // Subscribe to message publishers in Topic
 - InputField2      // Message input box
 - Btn6             // Send message button
 - Btn7             // Release Stream Channel button
 - Btn8             // Leave Stream Channel button
 - Btn9             // Leave Topic button
 - Btn10            // Unsubscribe from message publishers in Topic
 - Pannel           // Information output panel
     - Txt3         // Information output text
- EventSystem

Your interface should look similar to the following:

Implement Signaling

A complete code sample that implements the basic features of Signaling is presented here for your reference. To use the sample code, create a new script for the project. In Unity editor, from the Assets menu, select Create, then C# Script. Name the new script file HelloWorld.cs and paste the following code in the file:

Follow the implementation steps to understand the core API calls in the sample code or use the snippets in your own code.

Import Agora classes

To use the relevant Unity and Signaling APIs in your project, import the corresponding namespaces:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Agora.Rtm;

Initialize the Signaling engine

Before calling any other Signaling SDK API, initialize an IRtmClient instance.

if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(appId))
{
    ShowMessage("We need a userId and appId to initialize!");
    return;
}
RtmLogConfig logConfig = new RtmLogConfig();
// Set log file path
logConfig.filePath = "myFilePath";
// Set the file size of the agora.log file
logConfig.fileSizeInKB = 512;
// Set the log report level
logConfig.level = RTM_LOG_LEVEL.INFO;
RtmConfig config = new RtmConfig();
config.appId = appId;
config.userId = userId;
config.logConfig = logConfig;
// Create the RTM Client
try
{
    rtmClient = RtmClient.CreateAgoraRtmClient(config);
    ShowMessage("RTM Client Initialize Successful");
    // Inactive unnecessary components
    string[] activeComponentsList = { "Btn2" };
    string[] inactiveComponentList = { "Btn3", "Btn4", "Btn5", "Btn6", "Btn7", "Btn8", "Btn9", "Btn10" };
    ChangeComponentView(activeComponentsList, "ACTIVATE");
    ChangeComponentView(inactiveComponentList, "INACTIVATE");
}
catch (RTMException e)
{
    ShowMessage(string.Format("{0} is failed", e.Status.Operation));
    ShowMessage(string.Format("The error code is {0}, due to: {1}", e.Status.ErrorCode, e.Status.Reason));
}

Add an event listener

The event listener enables you to implement the processing logic in response to Signaling events. Use the following code to handle event notifications or display received messages:

private void OnConnectionStateChanged(string channelName, RTM_CONNECTION_STATE state, RTM_CONNECTION_CHANGE_REASON reason)
{
    ShowMessage(string.Format("Channel:{0} connection state have changed to:{1} because of {2}", channelName, state, reason));
}
// Implement the presence event handler
private void OnPresenceEvent(PresenceEvent eve)
{
    var channelName = eve.channelName;
    var channelType = eve.channelType;
    var eventType = eve.type;
    var publisher = eve.publisher;
    var stateItems = eve.stateItems;
    var interval = eve.interval;
    var snapshot = eve.snapshot;
    Debug.Log(string.Format("The Event : {0} Happend", eventType));
    switch (eventType)
    {
        case RTM_PRESENCE_EVENT_TYPE.SNAPSHOT:
            ShowMessage(string.Format("You have sub or join channel:{0} channe type is:{1}", channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.INTERVAL:
            ShowMessage(string.Format("The channel:{0} channe type is:{1} is now in interval mode!", channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.REMOTE_JOIN:
            ShowMessage(string.Format("User:{0} sub or join channel:{1} channe type is:{2}", publisher, channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.REMOTE_LEAVE:
            ShowMessage(string.Format("User:{0} unsub or leave channel:{1} channe type is:{2}", publisher, channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.REMOTE_TIMEOUT:
            ShowMessage(string.Format("User:{0} timeout from channel:{1} channe type is:{2}", publisher, channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.REMOTE_STATE_CHANGED:
            ShowMessage(string.Format("User:{0} state change in channel:{1} channe type is:{2}", publisher, channelName, channelType));
            break;
        case RTM_PRESENCE_EVENT_TYPE.ERROR_OUT_OF_SERVICE:
            ShowMessage(string.Format("User:{0} joined channel without presence service:{1} channe type is:{2}", publisher, channelName, channelType));
            break;
    }
}
// Implement the message event handler
private void OnMessageEvent(MessageEvent eve)
{
    var channelName = eve.channelName;
    var channelType = eve.channelType;
    var topic = eve.channelTopic;
    var publisher = eve.publisher;
    var messageType = eve.messageType;
    var customType = eve.customType;
    var message = eve.message;
    if (messageType == RTM_MESSAGE_TYPE.STRING)
    {
        var stMessage = message.GetData<string>();
        ShowMessage(string.Format("You have received a string type message: {0} from: {1} in channel:{2}", stMessage, publisher, channelName));
        ShowMessage(string.Format("The channel type is {0}", channelType));
    }
    else
    {
        var biMessage = message.GetData<byte[]>();
        ShowMessage(string.Format("You have received a binary type message: {0},from: {1} in channel:{2}", System.BitConverter.ToString(biMessage), publisher, channelName));
        ShowMessage(string.Format("The channel type is {0}", channelType));
    }
}

Log in to Signaling

To connect to Signaling and access Signaling network resources, such as sending messages, and subscribing to channels, call login.

During a login operation, the client attempts to establish a connection with Signaling. Once the connection is established, the client transmits heartbeat information to the Signaling server at fixed intervals to keep the client active until the client actively logs out or is disconnected. The connection is interrupted when timeout occurs. During this period, users may freely access the Signaling network resources subject to their own permissions and usage restrictions.

// Log in to Signaling
var result = await rtmClient.LoginAsync(token);
if (result.Status.Error)
{
    ShowMessage(string.Format("{0} is failed", result.Status.Operation));
    ShowMessage(string.Format("The error code is {0}, due to: {1}", result.Status.ErrorCode, result.Status.Reason));
}
else
{
    ShowMessage("Login Successfully");
}

Use the LoginAsync return value, or listen to the OnConnectionStateChanged event notification to confirm that login is successful or obtain the error code and cause of login failure. When performing a login operation, the client's network connection state is CONNECTING. After a successful login, the state is updated to CONNECTED.

Best practice

To continuously monitor the network connection state of the client, best practice is to continue to listen for OnConnectionStateChanged event notifications throughout the life cycle of the application. For further details, see Event listeners.

After a user successfully logs into Signaling, the application's PCU increases, which affects your billing data.

Send a message

To distribute a message to all subscribers of a message channel, call PublishAsync. The following code sends a string type message.

// Send a message to a channel
var message = GameObject.Find("InputField1").GetComponent<InputField>().text;
if (rtmClient != null)
{
    PublishOptions options = new PublishOptions()
    {
        channelType = RTM_CHANNEL_TYPE.MESSAGE,
        customType = "PlainText"
    };
    var result = await rtmClient.PublishAsync(msChannelName, message, options);
    if (result.Status.Error)
    {
        ShowMessage(string.Format("{0} is failed, The error code is {1}", result.Status.Operation, result.Status.ErrorCode));
    }
    else
    {
        ShowMessage("Publish Message Success!");
    }
}

Before calling PublishAsync to send a message, serialize the message payload as a string.

Subscribe and unsubscribe

To receive messages sent to a channel, call SubscribeAsync to subscribe to channel messages:

//Subscribe to a Message Channel
SubscribeOptions options = new SubscribeOptions()
{
    withMessage = true,
    withPresence = true
};
var result2 = await rtmClient.SubscribeAsync(msChannelName, options);
if (result2.Status.Error)
{
    ShowMessage(string.Format("{0} is failed", result2.Status.Operation));
    ShowMessage(string.Format("The error code is {0}, due to: {1}", result2.Status.ErrorCode, result2.Status.Reason));
}
else
{
    ShowMessage(string.Format("Subscribe channel success! at Channel:{0}", result2.Response.ChannelName));
}

When you no longer need to receive messages from a channel, call UnsubscribeAsync to unsubscribe from the channel:

if (rtmClient != null)
{
    var result = await rtmClient.UnsubscribeAsync(msChannelName);
    if (result.Status.Error)
    {
        Debug.Log(string.Format("{0} is failed", result.Status.Operation));
        Debug.Log(string.Format("The error code is {0}, because of: {1}", result.Status.ErrorCode, result.Status.Reason));
    }
    else
    {
        Debug.Log("Unsubscribe Channel Success!");
    }
    var status3 = rtmClient.Dispose();
    Debug.Log("Dispose rtmClient Success!");
    rtmClient = null;
}

For more information about sending and receiving messages see Message channels and Stream channels.

Log out of Signaling

When a user no longer needs to use Signaling, call LogoutAsync. Logging out means closing the connection between the client and Signaling. The user is automatically logged out or unsubscribed from all message and stream channels. Other users in the channel receive an OnPresenceEvent notification of the user leaving the channel.

// Logout of Signaling
var result = await rtmClient.LogoutAsync();

Test Signaling

Take the following steps to test the sample code:

  1. In your code, replace your_appId with your app ID from Agora Console and your_userId with a numeric string.

  2. Generate a temporary token for your project.

    1. In your code, replace your_token with the generated token.
  3. Repeat the previous step to generate a stream channel token but this time also fill in the channel name with the value for stChannelName and the User ID with the value for userId from your code. Use the generated token to replace your_RTC_token in your code.

  4. In the Unity Editor, mount the event handling functions defined in the code to the corresponding Button components.

  5. In Unity, click Play. You see the game running on your device.

  6. Run another instance of the game with the same appId but a different userId and tokens.

  7. In either game instance, type a message in the input box under Send string message to message channel and press Send Message.

    You see the message displayed in the other game instance.

    Congratulations! You have successfully integrated Signaling into your project.

Reference

This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product.

Token authentication

In this guide you retrieve a temporary token from Agora Console. To understand how to create an authentication server for development purposes, see Secure authentication with tokens.

API reference