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 app, 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 app listens for events.
To create a pub/sub session for Signaling, implement the following steps in your app:
Prerequisites
To implement the code presented on this page you need to have:
-
Enabled Signaling in Agora Console
-
A JavaScript package manager such as npm.
-
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
To create a folder for your project, and an index.html file for your app, execute the following commands in the terminal:
mkdir HelloWorld
cd HelloWorld
touch index.htmlIntegrate the SDK
Use either of the following methods to integrate Signaling SDK into your project.
Using CDN
-
Download the latest version of Signaling SDK for Web.
-
Add the following code to your project to reference the SDK:
<script src="path_to_sdk/agora-rtm.x.y.z.min.js"></script>Replace
x.y.zwith the specific SDK version number, such as 2.2.0. To get the latest version number, check the Release notes.
Using npm
-
Install the SDK using npm
npm install agora-rtm-sdk -
Import
AgoraRTMfrom the SDKimport AgoraRTM from 'agora-rtm-sdk';
Implement Signaling
A complete code sample that implements the basic features of Signaling is presented here for your reference. To use the sample code, copy the following lines into the index.html file:
Follow the implementation steps to understand the core API calls in the sample code or use the snippets in your own code.
Initialize the Signaling engine
Before calling any other Signaling SDK API, initialize an RTM object instance.
try {
const rtm = new RTM(appId, userId);
} catch (status) {
console.log("Error");
console.log(status);
}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:
// Message event handler.
rtm.addEventListener("message", event => {
showMessage(event.publisher, event.message);
});
// Presence event handler.
rtm.addEventListener("presence", event => {
if (event.eventType === "SNAPSHOT") {
showMessage("INFO", "I Join");
}
else {
showMessage("INFO", event.publisher + " is " + event.eventType);
}
});
// Link state changed event handler.
rtm.addEventListener("linkState", event => {
// The current link state.
const currentState = event.currentState;
// The reason why the link state changes.
const reason = event.reason;
showMessage("INFO", JSON.stringify(event));
});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
try {
const result = await rtm.login({ token: 'your_token' });
console.log(result);
} catch (status) {
console.log(status);
}Use the login return value, or listen to the status 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 status 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 publish. The following code sends a string type message.
// Send a message to a channel
const publishMessage = async (message) => {
const payload = { type: "text", message: message };
const publishMessage = JSON.stringify(payload);
const publishOptions = { channelType: 'MESSAGE'}
try {
const result = await rtm.publish(msChannelName, publishMessage, publishOptions);
showMessage(userId, publishMessage);
console.log(result);
} catch (status) {
console.log(status);
}
}Before calling publish to send a message, serialize the message payload as a string.
Subscribe and unsubscribe
To receive messages sent to a channel, call subscribe to subscribe to channel messages:
// Subscribe to a channel
try {
const result = await rtm.subscribe(msChannelName);
console.log(result);
} catch (status) {
console.log(status);
}When you no longer need to receive messages from a channel, call unsubscribe to unsubscribe from the channel:
// Unsubscribe from a channel
try {
const result = await rtm.unsubscribe(msChannelName);
console.log(result);
} catch (status) {
console.log(status);
}
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 logout. 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 a presence notification of the user leaving the channel.
// Logout of Signaling
try {
const result = await rtm.logout();
} catch (status) {
const { operation, reason, errorCode } = status;
console.log(`${operation} failed, the error code is ${errorCode}, because of: ${reason}.`);
}Test Signaling
Take the following steps to test the sample code:
-
Generate a temporary token for your project.
-
In
index.html, replaceyour_appidandyour_tokenvalues in the code with your project's app ID and the generated token. -
Update the value for the
userIdwith an integer value. -
Save the file and run it in your browser.
-
Make a copy of the project. Use the same
app_idbut a differentuserId. Launch another instance of the page in a separate browser tab. -
Type a message in the text input box in either instance and click the Send button. The message is displayed in the other app instance.
-
Swap the sending and receiving instances and send another message.
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.
Sample project
Explore and experiment with the Signaling Online demo. To download and customize the source code, refer to the GitHub repository.
